我正在尝试在 John Zelle 的“Python Programming: An Introduction to Computer Science”中做一个练习。我为他的书下载了一个特殊的图形包(graphics.py,在链接的网站上)。问题如下:
编写一个程序,将彩色图像转换为灰度图像。用户提供包含 GIF 或 PPM 图像的文件名,程序加载图像并显示文件。单击鼠标,程序将图像转换为灰度。然后提示用户输入文件名以存储灰度图像。
您可能需要返回并查看图形库中的 Image 对象(第 4.8.4 节)。转换图像的基本思想是逐个像素地遍历它,并将每个图像从颜色转换为适当的灰色阴影。通过将其红色、绿色和蓝色分量设置为具有相同亮度而创建的灰色像素。所以,color_rgb(0, 0, 0)
是黑色的,color_rgb(255, 255, 255)
是白色的,color_rgb(127, 127, 127)
是介于两者之间的灰色“中间”。您应该使用原始 rgb 值的加权平均值来确定灰色的亮度。这是灰度算法的伪代码[由于某种原因,四空格缩进在预览中不起作用]:
for each row in the image:
for each column in the image:
r, g, b = get pixel information for current row and column
brightness = int(round(0.299r + 0.587g + 0.114b))
update the image # to see progress row by row
注意:Image
类中的像素操作相当慢,因此您需要使用相对较小的图像(不是12 兆像素)来测试您的程序。
我已经为此工作了几个小时。这是我的代码的最新版本:
# grayscale.py
from graphics import *
def main():
infileName = input("File name: ")
outfileName = input("Save to: ")
image = Image(Point(100,100), infileName)
width = image.getWidth()
height = image.getHeight()
win = GraphWin("rgb")
image.draw(win)
row = 0
column = 0
win.getMouse()
for row in range(200):
for column in range(200):
r, g, b = image.getPixel(row, column)
brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b))
image.setPixel(row, column, color_rgb(brightness, brightness, brightness))
win.update()
win.getMouse()
win.close()
main()
我终于明白了,所以 Python 没有给我任何错误消息。但程序所做的只是加载图像,单击几下鼠标,然后关闭。我一直将输入文件输入为 U:\My Pictures\yay.gif,并将输出文件输入为 U:\My Pictures\yay2.gif。但我刚刚搜索了我的电脑,U:\My Pictures\yay2.gif 不存在。我究竟做错了什么?顺便说一句,这不适合上课——我没有老师可以问。
也许我应该在帖子中跟进。我添加了保存功能,但我得到了一个带有 200x200 灰度框的图像,其余部分是彩色的。所以,这里有一些我改变的行:
win = GraphWin("rgb", width, height)
for row in range(height):
for column in range(width):
我收到以下错误消息: Traceback(最近一次调用最后一次):
文件“C:\Python31\grayscale.py”,第 31 行,在
main()
文件“C:\Python31\grayscale.py”,第 22 行,在 main
r, g, b = image.getPixel(row, column)
文件“C:\Python31\lib\graphics.py”,第 810 行,在 getPixel
值 = self.img.get(x,y)
文件“C :\Python31\lib\tkinter_ init _.py", line 3301, in get
return self.tk.call(self.name, 'get', x, y)
_tkinter.TclError: pyimage1 get: 坐标超出范围
我知道我可能需要将图像的锚点更改为中心。但我只能通过图像的宽度和高度来确定,而且我必须先上传图像才能获得这些值。有解决方法吗?