import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os.path
img_path = "E:\\test.jpg"
img = Image.open(img_path)
img = np.asarray(img)
flat = img.flatten()
def get_histogram(image, bins):
histogram = np.zeros(bins)
for pixel in image:
histogram[pixel] += 1
return histogram
hist = get_histogram(flat, 256)
cs = np.cumsum(hist)
nj = (cs - cs.min()) * 255
N = cs.max() - cs.min()
cs = nj / N
cs = cs.astype('uint8')
img_new = cs[flat]
img_new = np.reshape(img_new, img.shape)
fig = plt.figure()
fig.set_figheight(15)
fig.set_figwidth(15)
fig.add_subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title("Image 'Before' Contrast Adjustment")
fig.add_subplot(1, 2, 2)
plt.imshow(img_new, cmap='gray')
plt.title("Image 'After' Contrast Adjustment")
filename = os.path.basename(img_path)
plt.show()