<jupyter_start><jupyter_text>13. Histogram Specification<jupyter_code>import numpy as np
import pandas as pd
import cv2
from collections import Counter

%matplotlib inline
import matplotlib.pyplot as plt

def histogram_equalization(data, L):
    
    total_sum= np.sum(data[:, 1])
    cdf= 0
    table= []
    for row in data:
        pdf= row[1]/total_sum
        cdf+= pdf
        r= list(row)
        r.extend([pdf, cdf, round(cdf*(L-1), 0)])
        table.append(r)
    table= np.array(table)
    
    df= pd.DataFrame(table, columns= ['Gray Levels', 'No. of pixels', 'PDF', 'CDF', '(L-1)*CDF'])
    
    new_data= [0 for i in range(L)]
    for i in range(len(data)):
        new_data[int(table[i,4])]+= data[i, 1]
    
    hist_data=[]
    for i in range(L):
        hist_data.append([i, new_data[i]])
    hist_data= np.array(hist_data)
    
    return df, hist_data
def histogram_specification(data, c1, c2):
    D= []
    for i in range(len(c1)):
        for j in range(len(c2)):
            if c2[j]>= c1[i]:
                D.append(data[j, 0])
                break
    df= pd.DataFrame(np.array([data[:, 0], c1, c2, D]).T, columns= ['c0', 'c1', 'c2', 'D'])
    
    new_data= [0 for i in range(len(c1))]
    for i in range(len(data)):
        new_data[int(D[i])]+= data[i, 1]
    
    hist_data=[]
    for i in range(len(c1)):
        hist_data.append([i, new_data[i]])
    hist_data= np.array(hist_data)
    
    return df, hist_data<jupyter_output><empty_output><jupyter_text>User Data<jupyter_code># ip_data= []
# n= int(input("Enter no. of gray levels: "))
# for i in range(n):
#     gray_lvl, nos= map(int, input('Enter gray level and no. of pixel: ').split())
#     ip_data.append([gray_lvl, nos])
# ip_data= np.array(ip_data)

n= 8
ip_data= np.array([[0, 8],
 [1, 10],
 [2, 10],
 [3, 2],
 [4, 12],
 [5, 16],
 [6, 4],
 [7, 2]])
# des_data= []
# for i in range(n):
#     gray_lvl, nos= map(int, input('Enter gray level and no. of pixel: ').split())
#     des_data.append([gray_lvl, nos])
# des_data= np.array(des_data)

n= 8
des_data= np.array([[0, 0],
 [1, 0],
 [2, 0],
 [3, 0],
 [4, 20],
 [5, 20],
 [6, 16],
 [7, 8]])
ip_df, ip_hist_data= histogram_equalization(ip_data, n)
plt.bar(ip_data[:, 0], ip_data[:, 1], width= 0.1)
plt.title('Original Histogram')
plt.xlabel('Gray Levels')
plt.ylabel('No. of pixels')
plt.show()
ip_df.head(n)
plt.bar(ip_hist_data[:, 0], ip_hist_data[:, 1], width= 0.1)
plt.title('Equalized Histogram')
plt.xlabel('Gray Levels')
plt.ylabel('No. of pixels')
plt.show()
des_df, des_hist_data= histogram_equalization(des_data, n)
plt.bar(des_data[:, 0], des_data[:, 1], width= 0.1)
plt.title('Original Desired Histogram')
plt.xlabel('Gray Levels')
plt.ylabel('No. of pixels')
plt.show()
des_df.head(n)
plt.bar(des_hist_data[:, 0], des_hist_data[:, 1], width= 0.1)
plt.title('Desired Equalized Histogram')
plt.xlabel('Gray Levels')
plt.ylabel('No. of pixels')
plt.show()
sp_df, sp_hist_data= histogram_specification(ip_data, ip_df.loc[:, '(L-1)*CDF'], des_df.loc[:, '(L-1)*CDF'])
sp_df.head(n)
sp_hist_data
plt.bar(sp_hist_data[:, 0], sp_hist_data[:, 1], width= 0.1)
plt.title('Specified Histogram')
plt.xlabel('Gray Levels')
plt.ylabel('No. of pixels')
plt.show()<jupyter_output><empty_output><jupyter_text>Image<jupyter_code>def img2data(img, L):
    count= dict(Counter(img.ravel()))
    data_img= []
    for i in range(L):
        try:
            data_img.append([i, count[i]])
        except:
            data_img.append([i, 0])
    data_img= np.array(data_img)
    return data_img
ip1= input('Enter image name: ')
ip2= input('Enter desired image: ')

ip_img= cv2.imread(ip1)
des_img= cv2.imread(ip2)
ip_img= cv2.cvtColor(ip_img,cv2.COLOR_BGR2RGB)
des_img= cv2.cvtColor(des_img,cv2.COLOR_BGR2RGB)
ip_img.shape, des_img.shape
n= 256
ip_img0= ip_img[:, :, 0]
ip_img1= ip_img[:, :, 1]
ip_img2= ip_img[:, :, 2]

des_img0= des_img[:, :, 0]
des_img1= des_img[:, :, 1]
des_img2= des_img[:, :, 2]
ip_data0= img2data(ip_img0, 256)
ip_data1= img2data(ip_img1, 256)
ip_data2= img2data(ip_img2, 256)
des_data0= img2data(des_img0, 256)
des_data1= img2data(des_img1, 256)
des_data2= img2data(des_img2, 256)
ip_df0, ip_hist_data0= histogram_equalization(ip_data0, n)
ip_df1, ip_hist_data1= histogram_equalization(ip_data1, n)
ip_df2, ip_hist_data2= histogram_equalization(ip_data2, n)
fig, ax= plt.subplots(ncols= 3, figsize= (18, 4))
fsize= 14

ax[0].set_title("Original Histogram Red", fontsize= fsize)
ax[0].bar(ip_data0[:, 0], ip_data0[:, 1], width= 0.1, color='red')

ax[1].set_title("Original Histogram Green", fontsize= fsize)
ax[1].bar(ip_data1[:, 0], ip_data1[:, 1], width= 0.1, color='green')

ax[2].set_title("Original Histogram BLue", fontsize= fsize)
ax[2].bar(ip_data2[:, 0], ip_data2[:, 1], width= 0.1, color='blue')

plt.show()
ip_df0.head(10)
ip_df1.head(10)
ip_df2.head(10)
fig, ax= plt.subplots(ncols= 3, figsize= (18, 4))
fsize= 14

ax[0].set_title("Equalized Histogram Red", fontsize= fsize)
ax[0].bar(ip_hist_data0[:, 0], ip_hist_data0[:, 1], width= 0.1, color='red')

ax[1].set_title("Equalized Histogram Green", fontsize= fsize)
ax[1].bar(ip_hist_data1[:, 0], ip_hist_data1[:, 1], width= 0.1, color='green')

ax[2].set_title("Equalized Histogram BLue", fontsize= fsize)
ax[2].bar(ip_hist_data2[:, 0], ip_hist_data2[:, 1], width= 0.1, color='blue')

plt.show()
des_df0, des_hist_data0= histogram_equalization(des_data0, n)
des_df1, des_hist_data1= histogram_equalization(des_data1, n)
des_df2, des_hist_data2= histogram_equalization(des_data2, n)
fig, ax= plt.subplots(ncols= 3, figsize= (18, 4))
fsize= 14

ax[0].set_title("Original Desired Histogram Red", fontsize= fsize)
ax[0].bar(des_data0[:, 0], des_data0[:, 1], width= 0.1, color='red')

ax[1].set_title("Original Desired Histogram Green", fontsize= fsize)
ax[1].bar(des_data1[:, 0], des_data1[:, 1], width= 0.1, color='green')

ax[2].set_title("Original Desired Histogram BLue", fontsize= fsize)
ax[2].bar(des_data2[:, 0], des_data2[:, 1], width= 0.1, color='blue')

plt.show()
des_df0.head(10)
des_df1.head(10)
des_df2.head(10)
fig, ax= plt.subplots(ncols= 3, figsize= (18, 4))
fsize= 14

ax[0].set_title("Equalized Desired Histogram Red", fontsize= fsize)
ax[0].bar(des_hist_data0[:, 0], des_hist_data0[:, 1], width= 0.1, color='red')

ax[1].set_title("Equalized Desired Histogram Green", fontsize= fsize)
ax[1].bar(des_hist_data1[:, 0], des_hist_data1[:, 1], width= 0.1, color='green')

ax[2].set_title("Equalized Desired Histogram Blue", fontsize= fsize)
ax[2].bar(des_hist_data2[:, 0], des_hist_data2[:, 1], width= 0.1, color='blue')

plt.show()
sp_df0, sp_hist_data0= histogram_specification(ip_data0, ip_df0.loc[:, '(L-1)*CDF'], des_df0.loc[:, '(L-1)*CDF'])
sp_df1, sp_hist_data1= histogram_specification(ip_data1, ip_df1.loc[:, '(L-1)*CDF'], des_df1.loc[:, '(L-1)*CDF'])
sp_df2, sp_hist_data2= histogram_specification(ip_data2, ip_df2.loc[:, '(L-1)*CDF'], des_df2.loc[:, '(L-1)*CDF'])
sp_df0.head(10)
sp_df1.head(10)
sp_df2.head(10)
fig, ax= plt.subplots(ncols= 3, figsize= (18, 4))
fsize= 14

ax[0].set_title("Equalized spired Histogram Red", fontsize= fsize)
ax[0].bar(sp_hist_data0[:, 0], sp_hist_data0[:, 1], width= 0.1, color='red')

ax[1].set_title("Equalized spired Histogram Green", fontsize= fsize)
ax[1].bar(sp_hist_data1[:, 0], sp_hist_data1[:, 1], width= 0.1, color='green')

ax[2].set_title("Equalized spired Histogram BLue", fontsize= fsize)
ax[2].bar(sp_hist_data2[:, 0], sp_hist_data2[:, 1], width= 0.1, color='blue')

plt.show()
def data2img(img, df):
    new_img= img.copy()
    for i in range(df.shape[0]):
        new_img[img==i]= df.loc[i, 'D']
    return new_img
new_img0= data2img(ip_img0, sp_df0)
new_img1= data2img(ip_img1, sp_df1)
new_img2= data2img(ip_img2, sp_df2)
new_img= np.array([new_img0.T, new_img1.T, new_img2.T]).T
new_img.shape
fig, ax= plt.subplots(ncols= 3, figsize= (18, 6))
fsize= 14

ax[0].set_title("Original Image", fontsize= fsize)
ax[0].imshow(ip_img)

ax[1].set_title("Desired Image", fontsize= fsize)
ax[1].imshow(des_img)

ax[2].set_title("After histogram specification", fontsize= fsize)
ax[2].imshow(new_img)

plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.18928571428571428, 'fraction_numerical': 0.049507389162561574, 'mean_word_length': 5.124434389140271, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '453212', 'license': 'MIT', 'n_tokens_mistral': 3679, 'n_tokens_neox': 3514, 'n_words': 737, 'path': '13. Histogram Specification.ipynb', 'repo_name': 'mohitbansal964/Image-Processing-Algorithms', 'size': '8120'}