This is my take on an image → greyscale converter.
#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, win):
width = image2convert.getWidth()
height = image2convert.getHeight()
#For each row of pixels
for pixelx in range(width):
#For each column of pixels
for pixely in range(height):
print("Converted pixel: x:{0} y: {1}".format(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
win.update()
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, win)
#save new image
outFile = asksaveasfilename(filetypes=[("GIF-Image", ".gif"), ("PPM-Image", ".ppm")])
newImg = image2convert.save(outFile)
#close file and window after click
win.getMouse()
image2convert.close()
win.close()
main()
Opinions/Suggestions/Ideas? It is pretty slow, but I don't think that this approach can be much faster.
convert()
, how doesupdate(win)
work?win
doesn't seem to be in scope there. \$\endgroup\$