Skip to content

Instantly share code, notes, and snippets.

@robdanet
Created July 18, 2021 15:27
Show Gist options
  • Save robdanet/ddc85b2d18fbc676d8e68f076d06a63a to your computer and use it in GitHub Desktop.
Save robdanet/ddc85b2d18fbc676d8e68f076d06a63a to your computer and use it in GitHub Desktop.
How to modify an image's brightness in python
## Original code from the series on image processing in python
## Read the tutorial at https://thesourcecodenotes.blogspot.com/search/label/brightness
from PIL import Image, ImageTk
import tkinter as tk
def brightness(input_image, value):
if input_image.mode != 'L' and input_image.mode != 'P':
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))
output_image.putpixel((x,y), int(pix + value))
return output_image
def main():
root = tk.Tk()
img = Image.open("retriver_gray.png", formats=['PNG'])
width = img.width*2+20
height = img.height
root.geometry(f'{width}x{height}')
output_im = brightness(img, 50)
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's mode must be 'L' or 'P'"\
"Check https://pillow.readthedocs.io/en/"\
"latest/handbook/concepts.html#concept-modes")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment