Skip to content

Instantly share code, notes, and snippets.

@robdanet
Created July 18, 2021 15:16
Show Gist options
  • Save robdanet/adcfec7bb6e97a8472a1dc7bd09dc247 to your computer and use it in GitHub Desktop.
Save robdanet/adcfec7bb6e97a8472a1dc7bd09dc247 to your computer and use it in GitHub Desktop.
RGB to Grayscale in Python
## Original code from the series on image processing in python
## Read the tutorial at https://thesourcecodenotes.blogspot.com/2021/07/image-processing-in-python.html
from PIL import Image, ImageTk
import tkinter as tk
def rgb2gray(input_image):
if input_image.mode != 'RGB':
return None
else:
output_image = Image.new('L', (input_image.width,
input_image.height))
for x in range(input_image.width):
for y in range(input_image.height):
pix = input_image.getpixel((x, y))
pix = int(int(pix[0]*0.299)+
int(pix[1]*0.587)+
int(pix[2]*0.114))
output_image.putpixel((x,y), pix)
return output_image
if __name__ == "__main__":
root = tk.Tk()
img = Image.open("retriver.png")
width = img.width*2+20
height = img.height
root.geometry(f'{width}x{height}')
output_im = rgb2gray(img)
if output_im != None:
output_im = ImageTk.PhotoImage(output_im)
input_im = ImageTk.PhotoImage(img)
canvas = tk.Canvas(root, width=width, height=height, bg="#ffffff")
canvas.create_image(width/4-1, height/2-1, image=input_im, state="normal")
canvas.create_image(20+3*img.width/2-1, img.height/2-1, image=output_im, state="normal")
canvas.place(x=0, y=0)
canvas.pack()
root.mainloop()
else:
print("Input image must be in 'RGB' colour space")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment