Skip to content

Instantly share code, notes, and snippets.

@robdanet
Created July 18, 2021 15:29
Show Gist options
  • Save robdanet/7fdb567da4c1c490af86a80d38193676 to your computer and use it in GitHub Desktop.
Save robdanet/7fdb567da4c1c490af86a80d38193676 to your computer and use it in GitHub Desktop.
How to modify an image's contrast in Python (contrast-stretching)
## Original code from the series on image processing in python
## Read the tutorial at https://thesourcecodenotes.blogspot.com/search/label/contrast-stretching
from PIL import Image, ImageTk
import tkinter as tk
def contrast(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-100) * 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 = contrast(img, 2.0)
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()
@robdanet
Copy link
Author

Head for the tutorial at https://thesourcecodenotes.blogspot.com/search/label/contrast-stretching to see how is done with colours images

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment