GIF / PPM到灰度转换器会引发错误“坐标超出范围”

时间:2019-02-15 08:38:15

标签: python python-3.x image converters

因此,我当前的练习是将用户选择的.gif或.ppm文件转换为灰度的程序。我得到了代码,从我收集的代码来看,它应该可以工作,但是在执行程序时出现错误。

Traceback (most recent call last):
  File ".\greyscale.py", line 54, in <module>
    main()
  File ".\greyscale.py", line 43, in main
    image2convert = convert(image2convert)
  File ".\greyscale.py", line 29, in convert
    r, g, b = image2convert.getPixel(pixelx, pixely)
  File "C:\Python37\lib\site-packages\graphics.py", line 933, in getPixel
    value = self.img.get(x,y)
  File "C:\Python37\lib\tkinter\__init__.py", line 3581, in get
    return self.tk.call(self.name, 'get', x, y)
_tkinter.TclError: pyimage1 get: coordinates out of range

这是我的代码:

#greyscale.py -- Converts an image file to greyscale

from tkinter.filedialog import askopenfilename, asksaveasfilename
from graphics import *

def displayimage(imagefile):
    #Open image to get width and height
    image2convert = Image(Point(0, 0), imagefile)
    imgwidth = image2convert.getWidth()
    imgheight = image2convert.getHeight()

    #Set window size to image size and draw image to window
    win = GraphWin("Greyscale Converter", imgwidth, imgheight)
    image2convert.move(imgwidth/2, imgheight/2)
    image2convert.draw(win)

    return image2convert, win

def convert(image2convert):
    width = image2convert.getWidth()
    height = image2convert.getHeight()

    #For each row of pixels
    for pixelx in range(width + 1):
        #For each column of pixels
        for pixely in range(height + 1):
            print(pixelx, pixely)
            #Get Pixel Colour, calculate greyscale, set Pixel to calculated colour
            r, g, b = image2convert.getPixel(pixelx, pixely)
            brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b))
            image2convert.setPixel(pixelx, pixely, color_rgb(brightness, brightness, brightness))
        #See progress for each row
        update(win)
    return image2convert

def main():
    imagefile = askopenfilename(filetypes=[("GIF-Image", ".gif"), ("PPM-Image", ".ppm")])

    image2convert, win = displayimage(imagefile)

    #convert after click
    win.getMouse()
    image2convert = convert(image2convert)

    #save new image
    outFile = asksaveasfilename(image2convert)
    newImg = image2convert.save(outFile)

    #close file and window after click
    win.getMouse()
    image2convert.close()
    win.close()

main()

获取像素以x和y坐标为参数并输出颜色值列表-> [r,g,b]

我真的不明白为什么它不起作用,我每次都使用print输出x,y值,而且看起来也很正确:

0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
0 10
0 11
0 12
0 13
0 14
0 15
0 16
0 17
0 18
0 19
0 20
0 21
0 22
0 23
0 24
0 25
0 26
0 27
0 28
0 29
0 30
....

因此,它在第一个循环中正确遍历了每个像素,但随后无法获得像素颜色。

有什么想法吗?

0 个答案:

没有答案