Monday, June 13, 2016

Image Processing - Histogram Equalization - Part 2

Draw Histograms

# draw flattened histogram
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
%matplotlib inline

im = Image.open("sample.jpg")
im_arr = np.array(im)
print im_arr.shape

plt.figure(figsize=(15,5))
plt.subplot(1,2,1)
plt.imshow(im_arr)
plt.axis('off')

plt.subplot(1,2,2)
im_r = im_arr[:,:,0].flatten() # 3d (r,g,b) to 1d (stacked)
im_g = im_arr[:,:,1].flatten()
im_b = im_arr[:,:,2].flatten()
imhist, bins = np.histogram(im_r, 256, normed=True) #bins are a sequence of data range
plt.plot(imhist, label="Red")
imhist, bins = np.histogram(im_g, 256, normed=True)
plt.plot(imhist, label="Green")
imhist, bins = np.histogram(im_b, 256, normed=True)
plt.plot(imhist, label="Blue")
plt.legend(loc=1)

Histogram Equalization on Grayscale Image

# histogram equalization
def histeq(im, nbr_bins=256):
    imhist,bins = np.histogram(im.flatten(),nbr_bins,normed=True)
    cdf = imhist.cumsum() # cumulative distribution function (cumulative sum)
    cdf = 255 * cdf / cdf[-1] # normalization (brilliant! cdf[-1] is the sum of all)
    im2 = np.interp(im.flatten(), bins[:-1], cdf) # (x', x, fx) linear interpolate x' accordingg to x -> f(x)
    return im2.reshape(im.shape), cdf

im_gray = np.array(im.convert('L')) # interpolate in grayscale
im2, cdf = histeq(im_gray) # increase the dark area

plt.figure(figsize=(15,10))
plt.subplot(2,2,1)
plt.imshow(im_gray,cmap='gray')

plt.subplot(2,2,2)
plt.imshow(im2,cmap='gray')

plt.subplot(2,2,3)
plt.plot(cdf, label="Cumulative Distribution Function")
plt.legend(loc=2)

imhist2, bins2 = np.histogram(im2, 256, normed=True)
plt.subplot(2,2,4)
plt.plot(imhist2, label="Equalized Historgram")
plt.legend(loc=1)

Histogram Equalization on Colored Image

im = Image.open("Luncheon.jpg")
im_arr = np.array(im)

img_r = im_arr[:,:,0]
img_g = im_arr[:,:,1]
img_b = im_arr[:,:,2]

im_r_eq, cdf = histeq(img_r)
im_g_eq, cdf = histeq(img_g)
im_b_eq, cdf = histeq(img_b)

im_eq = np.zeros(im_arr.shape, 'uint8')
print im_r_eq.shape
im_eq[:,:,0] = im_r_eq
im_eq[:,:,1] = im_g_eq
im_eq[:,:,2] = im_b_eq
print im_eq.shape

plt.figure(figsize=(15,10))
plt.subplot(2,3,1)
plt.imshow(im_r_eq, cmap="gray")
plt.axis('off')

plt.subplot(2,3,2)
plt.imshow(im_g_eq, cmap="gray")
plt.axis('off')

plt.subplot(2,3,3)
plt.imshow(im_b_eq, cmap="gray")
plt.axis('off')

ime = Image.fromarray(im_eq)
plt.subplot(2,3,4)
plt.imshow(ime)
plt.axis('off')

plt.subplot(2,3,5)
plt.imshow(im)
plt.axis('off')

No comments:

Post a Comment

Myriad

Visitors