Amazing-Python-Scripts
71 строка · 1.7 Кб
1import numpy as np2import matplotlib.pyplot as plt3from PIL import Image4import os.path5
6# example -> C:\Users\xyz\OneDrive\Desktop\project\image.jpg
7img_path = input("Enter the path here: ")8img = Image.open(img_path)9
10# convert our image into a numpy array
11img = np.asarray(img)12# print(img.shape)
13# put pixels in a 1D array by flattening out img array
14flat = img.flatten()15
16# create our own histogram function
17
18
19def get_histogram(image, bins):20# array with size of bins, set to zeros21histogram = np.zeros(bins)22
23# loop through pixels and sum up counts of pixels24for pixel in image:25histogram[pixel] += 126
27# return our final result28return histogram29
30
31# execute our histogram function
32hist = get_histogram(flat, 256)33
34# execute the fn
35cs = np.cumsum(hist)36
37# numerator & denomenator
38nj = (cs - cs.min()) * 25539N = cs.max() - cs.min()40
41# re-normalize the cumsum
42cs = nj / N43
44# cast it back to uint8 since we can't use floating point values in images
45cs = cs.astype('uint8')46
47# get the value from cumulative sum for every index in flat, and set that as img_new
48img_new = cs[flat]49
50# put array back into original shape since we flattened it
51img_new = np.reshape(img_new, img.shape)52
53# set up side-by-side image display
54fig = plt.figure()55fig.set_figheight(15)56fig.set_figwidth(15)57
58# display the real image
59fig.add_subplot(1, 2, 1)60plt.imshow(img, cmap='gray')61plt.title("Image 'Before' Contrast Adjustment")62
63# display the new image
64fig.add_subplot(1, 2, 2)65plt.imshow(img_new, cmap='gray')66plt.title("Image 'After' Contrast Adjustment")67filename = os.path.basename(img_path)68
69plt.savefig("./Image Contrast Adjusting Filter/(Contrast Adjusted)"+filename)70
71plt.show()72