In: Computer Science
Language Python
with functions and one main function
Write a program that converts a color image to grayscale. The user supplies the name of a file containing a GIF or PPM image, and the program loads the image and displays the file. At the click of the mouse, the program converts the image to grayscale. The user is then prompted for a file name to store the grayscale image in.
code
solution
//output
//colorful.gif
//output.gif
//copyable code
from tkinter import *
from PIL import ImageTk, Image
#FUNCTION grayscale
def grayscale(event):
#loading image
img_pixels=img.load()
#loop for row and column
for i1 in range(img.size[0]):
for j1 in range(img.size[1]):
#rbg image
rgbsum=sum(img_pixels[i1,j1])
#calculate average
avg1=rgbsum//3
# red, green, blue value
img_pixels[i,j]=(avg1,avg1,avg1)
#update image
photo_img = ImageTk.PhotoImage(img)
imglabel.configure(image=photo_img)
imglabel.image=photo_img
#create a window
root = Tk()
#read a file
input_name=input('please Enter the input file name: ')
#open a image file
img=Image.open(input_name)
#creating a PhotoImage
photoimg = ImageTk.PhotoImage(img)
#create label
imglabel = Label(root, image=photoimg)
imglabel.bind("<Button>",grayscale)
imglabel.grid(row=1, column=1)
#main method
root.mainloop()
#getting output file name
output=input('please Enter the output file name: ')
img.save(output)