【问题标题】:Tkinter Python - Converting an image to black and whiteTkinter Python - 将图像转换为黑白
【发布时间】:2021-02-27 06:45:23
【问题描述】:

我仍在尝试弄清楚如何将图像转换为黑白。

我有一个带有命令按钮的 GUI,上面写着“将图像转换为黑白”。我将该命令绑定到def bAndW(self)。它在 GUI 上加载当前图像,但不会转换为黑白。

下面是代码:

def bAndW(self):

    from images import Image

    LoadAFile = self.inputText.getText()
    CurrentImage = open(LoadAFile)
    image = Image(LoadAFile)
    image.draw()
    BlackAndWhite(image)
    image.draw()
    #self.imageLabel["image"] = self.image


def BlackAndWhite(image):       
      
    blackPixel = (0,0,0)
    whitePixel = (255,255,255)
    
    for y in range(image.getHeight()):
        for x in range(image.getWidth()):
            (r, g, b) = image.getPixel(x,y)
            average = (r + b + g) /3
            if average < 128:
                image.setPixel(x,y,blackPixel)
            else:
                image.setPixel(x,y, whitePixel)

这是错误信息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
    return self.func(*args)
  File "/Users/movio/Desktop/CSCI/P6.1.py", line 50, in bAndW
    BlackAndWhite(image)
NameError: name 'BlackAndWhite' is not defined

【问题讨论】:

  • 如果BlackAndWhite() 是同一个类中的函数,则应该使用self.BlackAndWhite(image)。也应该使用def BlackAndWhite(self, image)
  • 我相信 PIL 有一个功能可以做到这一点。

标签: python python-3.x python-2.7 tkinter


【解决方案1】:

正如 acw1668 所说,

如果 BlackAndWhite() 是同一个类中的函数, 应该使用 self.BlackAndWhite(image)。还有 def BlackAndWhite(self, 图片)也应该使用

这应该可以解决您的错误。 此外,您可以使用 PILLOW 库,而不是编写自己的函数来将图像转换为黑白,该库为您提供了一个简单的函数。

from PIL import Image

    def bAndW(self):
        LoadAFile = "image_to_open.png"
        img = Image.open(LoadAFile)
        img.convert("L")

这里,convert() 方法将图像转换为灰度(黑白)图像。

【讨论】:

  • 根据 OP 代码,OP 想要真正的黑白(即只有两种颜色)图像。所以应该改用convert("1")
猜你喜欢
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
相关资源
最近更新 更多