You are on page 1of 11

DEPARTMENT OF COMPUTER & SOFTWARE

ENGINEERING

COLLEGE OF E&ME, NUST, RAWALPINDI

EC312 Digital Image Processing


Lab Report - 05

SUBMITTED TO:
LE Ma’am Sundas Ashraf

SUBMITTED BY:
Uzair Waheed
Reg # 371828
DE- 43 CE

Submission Date:13/03/24

1|Page
Lab-05: Histogram Equalization
Lab Tasks
Task-1:
Apply contrast stretching on the image of car provided by setting 5th and 95th
percentiles of the input values to 0 and 255 respectively.
Code:
import cv2
import numpy as np

img = cv2.imread('inp_image.jpg', 0)
cv2.imshow("Real Image:", img)

def contrast_stretching(img, lp, hp):


min_val = np.percentile(img, lp)
max_val = np.percentile(img, hp)

rows, cols = img.shape


for i in range(rows):
for j in range(cols):
if img[i][j] <= min_val:
img[i][j] = 0
elif img[i][j] >= max_val:
img[i][j] = 255
else:
img[i][j] = ((img[i][j] - min_val) / (max_val - min_val)) *
255

contrast_stretching(img, 5, 95)
cv2.imshow("after Contrast Stretching", img)
cv2.waitKey(0)

2|Page
Output:

Task-2:
Now apply Histogram equalization on the same image.

i. Calculate the histogram of the image save it as Figure_1.jpg. (Don’t use any built-in
function of OpenCV or NumPy etc.)

ii. Calculate probability density function (PDF) from the histogram and save it as
Figure_2.jpg. PDF = H/(R*C). Where H is the Histogram and R and C is the number of
Rows and Columns of the image respectively.

iii. Calculate cumulative density function (CDF) and save it as Figure_3.jpg.

iv. Multiply the Cumulative PDF with 255 to find the transformation function then save
it as Figure_4.jpg

v. From the transformation function, replace the gray levels of the image to create
contrast enhanced(histogram equalized) image and save it as Figure_5.jpg

3|Page
vi. Calculate the histogram of the output image save it as Figure_6.jpg.

Code:

import cv2
import numpy as np
import matplotlib.pyplot as plt

def histogram(img):
rows, cols = img.shape
hist = np.zeros(256)
for x in range(rows):
for y in range(cols):
hist[img[x, y]] += 1
return hist

def plot_hist(histo, i, x_label):


plt.figure()
plt.bar(range(256), histo, color='lightblue')
plt.xlabel(x_label)
plt.ylabel('Frequency')
plt.title('Histogram')
plt.savefig("figure_" + str(i) + ".jpg")
plt.show()

img = cv2.imread("input.tif", 0)
cv2.imshow("Original Image", img)
# plot histogram of image
hist = histogram(img)
plot_hist(hist, 1, 'pixel_value')

# pdf
rows, cols = img.shape
pdf = hist / (rows * cols)
plot_hist(pdf, 2, 'pdf')

# cdf
cdf = np.zeros_like(pdf)
cdf[0] = pdf[0]
for i in range(len(pdf)):
cdf[i] = cdf[i - 1] + pdf[i]

plot_hist(cdf, 3, 'cdf')

# transformation
trans = cdf * 255
plot_hist(cdf, 4, 'transformation')

4|Page
# Enchanced Image
sk = np.round(trans).astype(int)

for i in range(rows):
for j in range(cols):
pixel = img[i, j]
img[i, j] = sk[pixel]

cv2.imshow("Enhanced Image", img)


cv2.imwrite("Figure_5.jpg", img)
cv2.waitKey(0)
histo = histogram(img)
plot_hist(histo, 6, 'Pixel_value')

Output:

5|Page
6|Page
Task-3:
Figure shows an 8 bit 512*512 image that at first glance appears to contain
five black squares on a gray background. The image is slightly noisy but noise
is imperceptible.
i. Apply global histogram equalization technique on the image.
ii. Apply local histogram equalization with a neighborhood of size 3*3.
Compare both histogram equalization techniques. The result of global
histogram equalization shows the significant enhancement of noise, aside
from noise it does not reveal any significant details from the original other
than a very faint hint that top left and bottom right squares contain an object
but from local histogram with neighborhood of size 3*3 we will see significant
detail contained within dark squares. //Figure reference 3.26 (a,b,c)

7|Page
Code:

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

def calculate_histogram(img):
histogram_values = np.zeros(256)
for x in range(0, img.shape[0]):
for y in range(0, img.shape[1]):
index = img[x][y]
histogram_values[index] = histogram_values[index] + 1

return histogram_values

def histogram_equalization(img):
histogram_values = calculate_histogram(img)
PDF = histogram_values * (1 / (img.shape[0] * img.shape[1]))
CDF = PDF
for x in range(1, 256):
CDF[x] = CDF[x] + CDF[x - 1]

transfer = CDF * 255


sk = np.round(transfer).astype(int)
new_img_ = np.zeros((img.shape[0], img.shape[1]), dtype="uint8")
for i in range(0, img.shape[0]):
for j in range(0, img.shape[1]):
new_img_[i, j] = sk[img[i, j]]
return new_img_

img = cv.imread("square_noisy.tif", 0)
cv.imshow("Original Image", img)
# cv.waitKey()
cv.imshow("After Global Equalization ", histogram_equalization(img))

new_img = np.zeros((img.shape[0], img.shape[1]), dtype="uint8")


for i in range(0, img.shape[0], 3):
for j in range(0, img.shape[1], 3):
temp = img[i:i + 3, j:j + 3]
new_img[i:i + 3, j:j + 3] = histogram_equalization(temp)
cv.imshow("After local Equalization", new_img)
cv.waitKey()

8|Page
Output:

9|Page
Task-4:
We have SEM (scanning electron microscope) image of tungsten filament
wrapped around a support. The filament in the center of the image and its
support are quite clear and easy to study. There is another filament structure
on the right, dark side of the image but it is almost imperceptible. Local
enhancement by contrast manipulation is an ideal approach to such
problems in which parts of an image may contain hidden features. You have
to apply the following techniques and compare their results. // Fig 3.27 (a,b,c)

i. Apply global histogram equalization technique on given image and save the
results.

ii. Enhance the image by using local histogram statistics.


Code:

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

def calculate_histogram(img):
histogram_values = np.zeros(256)
for x in range(0, img.shape[0]):
for y in range(0, img.shape[1]):
index = img[x][y]
histogram_values[index] = histogram_values[index] + 1

return histogram_values

def histogram_equalization(img):
histogram_values = calculate_histogram(img)
PDF = histogram_values * (1 / (img.shape[0] * img.shape[1]))
CDF = PDF
for x in range(1, 256):
CDF[x] = CDF[x] + CDF[x - 1]

transfer = CDF * 255


sk = np.round(transfer).astype(int)
new_img_ = np.zeros((img.shape[0], img.shape[1]), dtype="uint8")
for i in range(0, img.shape[0]):
for j in range(0, img.shape[1]):
new_img_[i, j] = sk[img[i, j]]
return new_img_

img = cv.imread("tungsten_original.tif", 0)

10 | P a g e
cv.imshow("Original Image", img)
# cv.waitKey()
cv.imshow("After Global Equalization ", histogram_equalization(img))

new_img = np.zeros((img.shape[0], img.shape[1]), dtype="uint8")


for i in range(0, img.shape[0], 3):
for j in range(0, img.shape[1], 3):
temp = img[i:i + 3, j:j + 3]
new_img[i:i + 3, j:j + 3] = histogram_equalization(temp)
cv.imshow("After local Equalization", new_img)
cv.waitKey()

Output:

11 | P a g e

You might also like