Created
July 20, 2021 00:22
-
-
Save robdanet/bf2dc5daaafb0c607aee7b1e5a15a6a1 to your computer and use it in GitHub Desktop.
Gray-level image histogram
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Original code from the series on image processing in python | |
## Read the tutorial at https://thesourcecodenotes.blogspot.com/2021/07/image-processing-in-python-4-grey-level.html | |
from PIL import Image, ImageTk | |
import tkinter as tk | |
def histogram(input_image): | |
if input_image.mode != 'L' and input_image.mode != 'P': | |
return None | |
else: | |
IHIST = [0 for i in range(256)] | |
HIST = [0 for i in range(256)] | |
SUM = 0 | |
for x in range(input_image.width): | |
for y in range(input_image.height): | |
pix = input_image.getpixel((x, y)) | |
IHIST[pix] = IHIST[pix]+1 | |
SUM += 1 | |
for i in range(256): | |
HIST[i] = float(IHIST[i]/SUM) | |
return HIST | |
def draw_histogram(canvas, IHIST, hist_w, hist_h): | |
## A bin is a bar of the histogram | |
bin_w = round(float(hist_w/512)) | |
offset = hist_w + 20 ## where we draw the first bin | |
for i in range(256): | |
canvas.create_line(bin_w*i+offset, hist_h, | |
bin_w*i+offset, hist_h-IHIST[i]) | |
if __name__=="__main__": | |
root = tk.Tk() | |
root.title("IMAGE GREY-LEVEL HISTOGRAM") | |
img = Image.open("retriver_gray.png") | |
width = img.width*2 | |
height = img.height | |
root.geometry(f'{width}x{height}') | |
IHIST = histogram(img) | |
if IHIST != None: | |
hist_w = img.width | |
hist_h = img.height | |
hist_max = max(IHIST) ## get the max value | |
## Normalize between 0 and hist_h | |
for i in range(256): | |
IHIST[i] = float(IHIST[i]/hist_max) * hist_h | |
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") | |
draw_histogram(canvas, IHIST, hist_w, hist_h) | |
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment