0% found this document useful (0 votes)
92 views

DRASHTI_CVML

This document is a laboratory journal for a B.Tech course in Computer Vision & Machine Learning at Dharmsinh Desai University. It includes a certificate of completion, an index of experiments, and detailed objectives, theories, sample programs, and conclusions for various image processing tasks using OpenCV. The experiments cover basic image processing functions, contrast enhancement algorithms, and other techniques relevant to the field.

Uploaded by

joshnap02619
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

DRASHTI_CVML

This document is a laboratory journal for a B.Tech course in Computer Vision & Machine Learning at Dharmsinh Desai University. It includes a certificate of completion, an index of experiments, and detailed objectives, theories, sample programs, and conclusions for various image processing tasks using OpenCV. The experiments cover basic image processing functions, contrast enhancement algorithms, and other techniques relevant to the field.

Uploaded by

joshnap02619
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Roll No: EC020

Laboratory Journal for

Computer Vision & Machine Learning

B. Tech.

SEM. VII (C2 Batch)

Department of Electronics & Communication


Faculty of Technology
Dharmsinh Desai University
Nadia
Dharmsinh Desai University
Faculty of Technology
College Road, Nadiad – 387001.
(Gujarat)

Certificate
This is to certify that the practical / term work carried out in the
subject of Computer Vision & Machine Learning and recorded
in this journal is the bonafide work of Miss. Drashti Prejiya
Roll No:EC020 Identity No:21ECUOG100 of B. Tech. Semester-
VII in the branch of Electronics & Communication during the
academic year 2024 - 2025.

(Prof. Pinkesh Patel) (Dr. Purvang Dalal)


Staff In-Charge Head of the Department
Date: Date:
INDEX

DATE
PAGE
NO. EXPERIMENT TITLE OF SIGN
NO.
EXPERIMENT
Basic Functions Of Image Processing With
1 OpenCV
1 3/7/2024

2 Fundamental Image Processing 5 10/7/2024

24/10/9/2
3 Contrast Enhancement Algorithms 11
0247/2024

4 Effect of Sampling & quantisation on an image 19 7/8/2024

5 spatial filters (smoothing & sharpening) 25 14/8/2024

6 image restoration 36 24/8/2024

7 color image processing 46 10/9/2024

8 image segmentation & morphological operation 55 18/9/2024

image classification using k-means clustering


9 algorithm
68 25/9/2024

image classification using k-means clustering 14/10/202


10 algorithm
72
4

11 supplementary assignment 81
Date: ____________
EXPERIMENT – 1
Basic Functions of Image Processing with OpenCV

OBJECTIVE:
I) To explore the basic functions of OpenCV.

THEORY:
OpenCV (Open-Source Computer Vision Library) is an essential tool for image processing and computer
vision tasks. It offers a wide range of functions to handle images effectively. In this experiment, we will
explore some fundamental OpenCV functions that are crucial for basic image processing operations:
imread(), imshow(), waitKey(), and destroyAllWindows().
1. imread(path, flag)
The imread() function is used to load an image from a file. It accepts two parameters:
● path: A string specifying the file path of the image. This can be either an absolute or relative
path.
● flag: The flag specifies the way how the image should be read.
o cv2.IMREAD_COLOR – It specifies to load a color image. Any transparency of image will
be neglected. It is the default flag. Alternatively, we can pass integer value 1 for this flag.
o cv2.IMREAD_GRAYSCALE – It specifies to load an image in grayscale mode.
Alternatively, we can pass integer value 0 for this flag.
o cv2.IMREAD_UNCHANGED – It specifies to load an image as such including alpha
channel. Alternatively, we can pass integer value -1 for this flag.
2. imshow(win_name, image)
The imshow() function displays an image in a new window. It takes two parameters
● win_name: A string representing the name of the window where the image will be shown.
● image: The image object to be displayed, which is returned by imread() or other processing
functions.
3. waitKey(delay):
The waitKey() function waits a key event for a specified duration. It is used to keep the image
window open and responsive. The function takes one parameter.
● delay: An integer representing the wait time in milliseconds. A value of 0 means the function
waits indefinitely until a key is pressed.
4. destroyAllWindows():

2
The destroyAllWindows() function allows users to destroy or close all windows at any time after
exiting the script.
SAMPLE PROGRAR:
1) READ, WRITE AND DISPLAYING AN IMAGES
import cv2

img = cv2.imread('gray2.jpg',0)
cv2.imshow("out1",img)
cv2.waitKey(0);
cv2.destroyAllWindows();

Output:

2) Display image properties

import cv2
img1 = cv2.imread('Fig0638(a)(lenna_RGB).tif',0)
print(type(img1))
print('image data type: ', img1.dtype)
print('row column: ', img1.shape)
print('dimension : ', img1.ndim)
print('image size: ', img1.size)
(nr,nc) = img1.shape # to access row and column of image
print('no. of row: ',nr)
print('no. of column: ', nc)
cv2.imshow('lena', img1)
cv2.waitkey(0) #wait until key strike from keyboard
cv2.destroyallwindow()#close all windows

Output:

3
<class 'numpy.ndarray'>
Image Data Type: uint8
Row Column: (300, 300)
Dimension : 2
Image Size: 90000
No. of Row: 300
No. of Column: 300

3) Color Image to Gray Scale Conversion


import cv2
img1 = cv2.imread('Fig0638(a)(lenna_RGB).tif', 1)
cv2.imshow('Color Image', img1)
cv2.waitKey(0)

cv2.destroyWindow('Color Image')
gray1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)
cv2.imshow('Gray Image', gray1)
cv2.waitKey(0) #Wait until key strike from keyboard
cv2.destroyAllWindow('Gray Image')#Close window

Output:

4) Image Resize
4
import cv2
import matplotlib.pyplot as plt
img1 = cv2.imread('Fig0638(a)(lenna_RGB).tif', 1)
cv2.imshow('Original Image', img1)
cv2.waitKey(0)
(row1,column1) = img1.shape # to access row and column of image
row2=150
column2=150
img2=cv2.resize(img1,(row2,column2), cv2.INTER_AREA)
cv2.imshow('Resized Image', img2)
cv2.waitKey(0)
print("Original Image Size:",img1.shape)
print("Resize Image Size:",img2.shape)

Output:

MODIFICATION:

To display multiple images in a single window using subplots.


Code:
import cv2
import matplotlib.pyplot as plt

img = cv2.imread('gray1.tif',0)
img1 = cv2.imread('gray3.tif',0)
img2 = cv2.imread('gray4.tif',0)

image = [ img, img1, img2 ]


title = ["out1", "out2", "out3"]
for i in range(3):
plt.subplot(1,3,i+1)
5
plt.imshow(image[i], cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()
Output:

CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
____

6
Date: ____________
EXPERIMENT – 2
Fundamental Image Processing

OBJECTIVE:
I) Find out average intensity of grayscale image.
II) Apply negative intensity transformation on any grayscale image.
SAMPLE PROGRAMS:
Objective – I:
Code:
import cv2
import matplotlib.pyplot as plt

img = cv2.imread('gray4.tif',0)
(M,N)=img.shape #Assign shape of img
cv2.imshow("out1",img)
cv2.waitKey(0);
cv2.destroyAllWindows();
avg=0
for i in range(M):
for j in range(N):
avg=avg+img[i][j]
intensity=avg/(M*N)
print("Average intensity=",intensity)

Image:

Output:
Average intensity= 118.7244873046875
7
Objective – II

Code:

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

img = cv2.imread('neg.tif',0)
print(img.shape)
(M,N)=img.shape #Assign shape of img
img2 = np.zeros((M,N),dtype='uint8')
for i in range(M):
for j in range(N):
img2[i][j]=255-img[i][j];

image = [ img, img2]


title = ["orignal img","negative img"]
for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

ASSIGNMENTS:
1) Read images having following characteristics and calculate average intensity of the same. (I) Darker
Image (II) Brighter Image.
Code:
import cv2
import matplotlib.pyplot as plt

img = cv2.imread('gray4.tif',0)
(M,N)=img.shape #Assign shape of img
cv2.imshow("out1",img)
8
cv2.waitKey(0);
cv2.destroyAllWindows();
avg=0
for i in range(M):
for j in range(N):
avg=avg+img[i][j]
intensity=avg/(M*N)
print("Average intensity=",intensity)

img1 = cv2.imread('dark_img.tif',0)
(M1,N1)=img1.shape #Assign shape of img
#img2 = np.zeros((M,N),dtype='uint8')
avg=0
for i in range(M1):
for j in range(N1):
avg=avg+img1[i][j]
intensity1=avg/(M1*N1)
print("avg. intensity=",intensity1)

img2 = cv2.imread('bright_img.tif',0)
(M2,N2)=img2.shape #Assign shape of img
#img2 = np.zeros((M,N),dtype='uint8')
avg=0
for i in range(M2):
for j in range(N2):
avg=avg+img2[i][j]
intensity2=avg/(M2*N2)
print("avg. intensity=",intensity2)

image = [ img1, img, img2 ]


title = [round(intensity1) ,round(intensity) , round(intensity2)]
for i in range(3):
plt.subplot(1,3,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

9
Average intensity of darker image = 118.7244873046875
avg. intensity of Average image = 0.881175875242331
avg. intensity of brighter image = 235.4876365565186

2) W.A.P. to perform Image Flipping operation on digital image.


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

def flip_horizontal(image):
m, n = image.shape
flipped = np.zeros((m,n),dtype='uint8')
for y in range(m):
for x in range(n):
flipped[y, x] = image[y, n - x - 1]
return flipped

def flip_vertical(image):
m, n = image.shape
flipped = np.zeros((m,n),dtype='uint8')
for y in range(m):
for x in range(n):
flipped[y, x] = image[m - y - 1, x]
return flipped

image = cv.imread(“face.tif”, 0)

flipped_horizontal = flip_horizontal(image)
flipped_vertical = flip_vertical(image)

img=[image, flipped_horizontal, flipped_vertical]


title=['Original','Flipped horizontal','Flipped vertical']

for i in range(3):
plt.subplot(1,3,i+1)
plt.imshow(img[i],cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

10
3) W.A.P. to perform to apply log transform on grayscale image.
Code:
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img=cv.imread(“log.tif”,0)
print(img.shape)

(nr,nc)=img.shape
img_log=np.zeros((nr,nc),dtype='uint8')
c=1

for i in range(nr):
for j in range(nc):
img_log[i][j]=c*(np.log(1+(img[i][j])))

image=[img,img_log]
title=['Original','Log transformed']

for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i],cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()
Result:

11
4) W.A.P. to perform gamma transform on grayscale image.
Code:
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img=cv.imread(“gamma”,0)
print(img.shape)

(nr,nc)=img.shape
img_log=np.zeros((nr,nc),dtype='uint8')
c=1
gamma=1.1

for i in range(nr):
for j in range(nc):
img_log[i][j]=c*((img[i][j])**gamma)

image=[img,img_log]
title=['Original','Log transformed(gamma=1.1, c=1)']

for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i],cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

12
CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
____

13
Date: ____________
EXPERIMENT – 3
Contrast Enhancement Algorithms

OBJECTIVE:
I) To observe histogram of grayscale image
II) To apply contrast stretching intensity transformation on grayscale image.
III) To observe bit-plane slicing of any grayscale image

SAMPLE PROGRAMS:
Objective – I:
import matplotlib.pyplot as plt
import cv2
import numpy as np

img = cv2.imread('gray1.tif',0)
(M,N)=img.shape
cv2.imshow("out1",img)
cv2.waitKey(0);
cv2.destroyAllWindows();
a=np.zeros(256,dtype='uint8')

for j in range(M):
for k in range(N):
i1=img[j][k]
a[i1]=a[i1]+1;
plt.plot(a)

Result:

14
Objective – II:
import cv2
import numpy as np
import matplotlib.pyplot as plt

r= cv2.imread('contra_str.tif',0)

(M,N)=r.shape
s=np.zeros((M,N),dtype='uint8')
r1=100
r2=129
s1=65
s2=235
for i in range(M):
for j in range(N):
if(r[i][j]<=r1) :
s[i][j]=(s1/r1)*r[i][j]
elif(r1<r[i][j]<r2):
s[i][j]=s1+((s2-s1)/(r2-r1))*(r[i][j]-r1)
else :
s[i][j]=255+((255-s2)/(255-r2))*(r[i][j]-255)

image = [ r,s]
title = ["orignal img", "contra streched img"]
for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

15
Objective – III:

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

def int2bin(n):

binary_str = bin(n)[2:]
binary_str = binary_str.zfill(8)
binary_str = binary_str[::-1]
binary_array = [int(bit) for bit in binary_str]

return binary_array[::-1]

img=cv.imread(“dollars”,0)
cv.imshow('ORG', img)
cv.waitKey(0)
cv.destroyAllWindows()

print(img.dtype)
(m,n)=img.shape
print(m,n)

img_bit=np.zeros((m,n,8),dtype='uint8')

for i in range(m):
for j in range(n):
img_bit[i][j]=int2bin(img[i][j])

title=['Original','8bit','7bit','6bit','5bit','4bit','3bit','2bit','1bit']

for i in range(9):
plt.subplot(3,3,i+1)
if i==0:
plt.imshow(img,cmap='gray')
else:
plt.imshow(img_bit[:,:,i-1],cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

16
ASSIGNMENT:
1) W.A.P. to perform histogram equalization on digital image.
Code:
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

image = cv.imread(“gray”,0)
M,N=image.shape
L=256

hist=np.zeros(L)
for i in range(M):
for j in range(N):
hist[image[i][j]] += 1

cdf = np.cumsum(hist)/(M*N)

equalized_image = np.zeros_like(image)
for i in range(M):
for j in range(N):
equalized_image[i][j] = np.round((L - 1) * cdf[image[i][j]]).astype(np.uint8)

equalized_hist = np.zeros(L)
for i in range(M):
for j in range(N):
equalized_hist[equalized_image[i, j]] += 1

plt.subplot(2, 2, 1)
plt.title('Original Image')
plt.xticks([])
17
plt.yticks([])
plt.imshow(image, cmap='gray')

plt.subplot(2, 2, 2)
plt.title('Equalized Image')
plt.xticks([])
plt.yticks([])
plt.imshow(equalized_image, cmap='gray')

plt.subplot(2, 2, 3)
plt.title('Original Histogram')
plt.xticks([])
plt.yticks([])
plt.plot(hist)

plt.subplot(2, 2, 4)
plt.title('Equalized Histogram')
plt.plot(equalized_hist)
plt.xticks([])
plt.yticks([])
plt.show()

Result:

CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________

18
EXPERIMENT – 4

EFFECT OF SAMPLING & QUANTIZATION ON AN IMAGE


OBJECTIVE:

I. To observe checker-board effect due to different sampling rate.


II. To observe false contouring effect due to number of gray level.

SAMPLE PROGRAM:

I. To observe checker-board effect due to different sampling rate


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

#21ECUOG100
img_drashti = cv2.imread('checker_board.tif',0)
(M,N)=img_drashti.shape
d=35
index_x=round(M/d)
index_y=round(N/d)
c=np.zeros((index_x,index_y),dtype='uint8')
for i in range (index_x):
for j in range (index_y):
c[i][j]=img_drashti[i*d][j*d]

cv2.imshow("out2",c)
cv2.waitKey(0);
cv2.destroyAllWindows();
image = [ img_drashti,c]
title = ["original img-EC020", "checkerboard effects"]
for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(title[i])
plt.show()
Result:

19
II.To observe false contouring effect due to number of gray level

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

# Read the image in grayscale


img = cv2.imread('Fig0809(a).tif', 0)

# Function to reduce the gray levels in an image


def reduce_gray_levels(image, num_levels):
max_val = 255
step_size = max_val // num_levels
result = np.floor(image / step_size) * step_size
return result.astype('uint8')

# Number of gray levels to simulate


gray_levels = [1, 2, 3, 4, 5, 6, 7, 8]

# List to store the images with reduced gray levels


quantized_images = [reduce_gray_levels(img, levels) for levels in gray_levels]

# Titles for the subplots


titles = [f'{levels} Gray Levels-EC020' for levels in gray_levels]

# Prepare for plotting


plt.figure(figsize=(12, 6))

# Plot the images with different gray levels in a 2x4 grid


for k in range(8):
plt.subplot(2, 4, k+1)
plt.imshow(quantized_images[k], cmap='gray')
plt.title(titles[k])
plt.xticks([])
plt.yticks([])

# Display the images


plt.tight_layout()
plt.show()

20
Result:

ASSIGNMENT:

(I) W.A.P. to observe False contouring effect due to no. of gray level. Keep only 4 gray
levels for observation.
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('Fig0809(a).tif',0)
# Create zeros array to store the stretched image
#21ECUOG100
final1 = np.zeros((img.shape[0],img.shape[1]),dtype = 'uint8')
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if (img[i][j]>=0 and img[i][j]<=80) :
final1[i,j] = 40
elif(img[i][j]>80 and img[i][j]<=160) :
final1[i,j] = 120
elif(img[i][j]>160 and img[i][j]<=200) :
final1[i,j] = 180
elif(img[i][j]>200 and img[i][j]<=255) :
final1[i,j] = 227
titles = ['Original Image-EC020', 'FalseContouringWith4IntensityLevel ']
images = [img,final1]

for k in range(2):
plt.subplot(1, 2, k+1)
plt.imshow(images[k],cmap='gray')
plt.title(titles[k])
plt.xticks([])

21
plt.yticks([])
plt.show()

Result:

(II) W.A.P. to observe checkerboard effect for different sampling rates.

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

# Read the image in grayscale


img = cv2.imread('checker_board.tif', 0)
(M, N) = img.shape

# Define the different sampling rates


sampling_rates = [5, 10, 15, 25, 35]

# Initialize a list to store the downsampled images


downsampled_images = []

# Create downsampled images for each sampling rate


for d in sampling_rates:
index_x = round(M / d)
index_y = round(N / d)
c = np.zeros((index_x, index_y), dtype='uint8')
for i in range(index_x):
for j in range(index_y):
c[i, j] = img[i * d, j * d] # Sample the pixel at intervals of d
downsampled_images.append(c)

# Prepare for plotting


plt.figure(figsize=(12, 8))

# Plot the original image


plt.subplot(2, 3, 1)
22
plt.imshow(img, cmap='gray')
plt.title("Original Image-EC020")
plt.xticks([])
plt.yticks([])

# Plot the downsampled images with checkerboard effects


for i, downsampled_img in enumerate(downsampled_images):
plt.subplot(2, 3, i + 2)
plt.imshow(downsampled_img, cmap='gray')
plt.title(f"Sampling Rate = {sampling_rates[i]}")
plt.xticks([])
plt.yticks([])

# Display the images


plt.tight_layout()
plt.show()

Result:

23
CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
___________________________________________________________________________________________________

24
EXPERIMENT – 5

SPATIAL FILTERS (SMOOTHING & SHARPNING)


OBJECTIVES:

I. To observe effect of various order of averaging filter on grayscale image.


II. W.A.P. to perform median filtering operation on a given noisy image.
III. Comparison performance of median and averaging filters to remove salt & pepper noise.
IV. To observe effect of various type of filtering mask on grayscale image.

THEORY:

Filtering is a technique for modifying or enhancing an image. Spatial domain operation or filtering (the
processed value for the current pixel processed value for the current pixel depends on both itself and
surrounding pixels). Hence, filtering is a neighbourhood operation, in which the value of any given pixel
in the output image is determined by applying some algorithm to the values of the pixels in the
neighbourhood of the corresponding input pixel. A pixel's neighbourhood is some set of pixels, defined
by their locations relative to that pixel. Filters are used for noise removal also.

Spatial filtering is of two types: (1) linear filtering in which response is decided by a mask is convolved
with respective image pixel values. E.g. smoothing filters, sharpening filters, (2) Non-linear filtering
where response is decided by arranging pixels values of neighborhood in order and selecting pixel as per
requirement. E.g. median filters, min or max filters.

SAMPLE PROGRAM:

I. To observe effect of various order of averaging filter (Linear Filter) on grayscale image.
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('ckt-board-saltpep-prob.pt05.tif',0)

# cv2.imshow("out1",img)
# cv2.waitKey(0);
# cv2.destroyAllWindows();

a=[0,3,9,13,17,21]
out1=np.zeros((1,6),dtype='uint8')
# cv2.imshow("out1",out)
# cv2.waitKey(0);
# cv2.destroyAllWindows();
25
# image = [ img, out]
title = ["original img-EC020","3*3","9*9","13*13","17*17","21*21"]
out1=[img,out1]
for i in range(6):
if (a[i]==0):
out1=img
else:
mask_drashti=(1/(a[i]*a[i]))*(np.ones((a[i],a[i]),dtype='uint8'))
out1=cv2.filter2D(img,-1,mask_drashti)

plt.subplot(2,3,i+1)
plt.imshow(out1, cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

II. W.A.P. to perform median filtering operation on a given noisy image.


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

# Read the image in grayscale


img = cv2.imread('ckt-board-saltpep-prob.pt05.tif', 0)

# List of different kernel sizes for the median filter


kernel_sizes = [0, 3, 9, 13, 17, 21]

# Titles for each filtered image


titles = ["Original Image-EC020", "3x3 Median Filter", "9x9 Median Filter", "13x13 Median
Filter", "17x17 Median Filter", "21x21 Median Filter"]

26
# Create a subplot for each filtered image
plt.figure(figsize=(12, 8))

# Loop over the kernel sizes and apply median filtering


for i in range(6):
if kernel_sizes[i] == 0:
# Show the original image
filtered_img = img
else:
# Apply median filter with different kernel sizes
filtered_img = cv2.medianBlur(img, kernel_sizes[i])

# Display the filtered images in a 2x3 grid


plt.subplot(2, 3, i+1)
plt.imshow(filtered_img, cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])

# Show the plot


plt.tight_layout()
plt.show()

Result:

27
III. Comparison performance of median and averaging filters to remove salt & pepper noise.
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('ckt-board-saltpep-prob.pt05.tif',0)
mask_drashti=(1/(5*5))*(np.ones((5,5),dtype='float32'))
out1=cv2.filter2D(img,-1,mask_drashti)
out2=cv2.medianBlur(img, 3)
image = [ img, out1, out2]
title = ["orignal img-EC020","avg. filter","median filter"]
out1=[img,out1]
for i in range(3):

plt.subplot(1,3,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

IV. To observe the effect of various types of filtering masks on grayscale images.
import cv2
import numpy as np
import matplotlib.pyplot as plt

# Read the grayscale image


img = cv2.imread('ckt-board-saltpep-prob.pt05.tif', 0)

28
# Apply different types of filters with a 3x3 kernel
# Max Filter
max_filter = cv2.dilate(img, np.ones((3,3), np.uint8))

# Min Filter
min_filter = cv2.erode(img, np.ones((3,3), np.uint8))

# Median Filter
median_filter = cv2.medianBlur(img, 3)

# Average Filter (using a 3x3 kernel)


avg_filter = cv2.blur(img, (3, 3))

# List of filtered images


filtered_images = [img, max_filter, min_filter, median_filter, avg_filter]

# Titles for the plots


titles = ["Original Image-EC020", "Max Filter", "Min Filter", "Median Filter", "Avg Filter"]

# Plot the images in a 2x3 grid


plt.figure(figsize=(10, 6))
for i in range(5):
plt.subplot(2, 3, i+1)
plt.imshow(filtered_images[i], cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])

# Show the plot


plt.tight_layout()
plt.show()

Result:

29
MODIFICATIONS:
I. Compare median and average filters with the size of the mask.
import cv2
import numpy as np
import matplotlib.pyplot as plt

# Read the grayscale image


img = cv2.imread('ckt-board-saltpep-prob.pt05.tif', 0)

# Apply Median and Average filters with 3x3 and 11x11 kernels
# Median Filter with 3x3 and 11x11 kernel
median_filter_3x3 = cv2.medianBlur(img, 3)
median_filter_11x11 = cv2.medianBlur(img, 11)

# Average Filter with 3x3 and 11x11 kernel


avg_filter_3x3 = cv2.blur(img, (3, 3))
avg_filter_11x11 = cv2.blur(img, (11, 11))

# List of filtered images


filtered_images = [img, median_filter_3x3, avg_filter_3x3, median_filter_11x11,
avg_filter_11x11]

# Titles for the plots


titles = ["Original Image-EC020", "Median Filter 3x3", "Avg Filter 3x3", "Median Filter
11x11", "Avg Filter 11x11"]

# Plot the images in a 2x3 grid


plt.figure(figsize=(12, 8))
for i in range(5):
plt.subplot(2, 3, i+1)
plt.imshow(filtered_images[i], cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])

# Show the plot


plt.tight_layout()
plt.show()

Result:

30
II. Vary amount of noise and compare output of both filters.
import cv2
import numpy as np
import matplotlib.pyplot as plt

# Function to add salt-and-pepper noise to the image


def add_salt_and_pepper_noise(image, amount):
noisy_img = image.copy()
# Add salt noise
num_salt = np.ceil(amount * image.size * 0.5)
coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape]
noisy_img[coords[0], coords[1]] = 255

# Add pepper noise


num_pepper = np.ceil(amount * image.size * 0.5)
coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape]
noisy_img[coords[0], coords[1]] = 0

return noisy_img

# Read the grayscale image


img = cv2.imread('Fig0809(a).tif', 0)

31
# Different noise levels to be added (amount of noise)
noise_levels = [0.01, 0.05, 0.1] # Low, medium, and high noise

# Prepare to store images for comparison


noisy_images = []
median_filtered = []
avg_filtered = []

# Apply noise and filters


for noise_amount in noise_levels:
noisy_img = add_salt_and_pepper_noise(img, noise_amount)
noisy_images.append(noisy_img)

# Apply Median and Average filters


median_filtered_img = cv2.medianBlur(noisy_img, 3)
avg_filtered_img = cv2.blur(noisy_img, (3, 3))

median_filtered.append(median_filtered_img)
avg_filtered.append(avg_filtered_img)

# Plot the original image


plt.figure(figsize=(12, 8))

# Plot the noisy images and their filtered versions


for i, noise_amount in enumerate(noise_levels):
# Noisy image
plt.subplot(3, 3, i * 3 + 1)
plt.imshow(noisy_images[i], cmap='gray')
plt.title(f'Noisy Image (Noise={noise_amount})-EC020')
plt.xticks([])
plt.yticks([])

# Median filtered image


plt.subplot(3, 3, i * 3 + 2)
plt.imshow(median_filtered[i], cmap='gray')
plt.title(f'Median Filter (Noise={noise_amount})')
plt.xticks([])
plt.yticks([])

# Average filtered image


plt.subplot(3, 3, i * 3 + 3)
plt.imshow(avg_filtered[i], cmap='gray')

32
plt.title(f'Avg Filter (Noise={noise_amount})')
plt.xticks([])
plt.yticks([])

# Display the plot


plt.tight_layout()
plt.show()

Result:

III. To observe the effect of laplacian sharpening filter on grayscale image.


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

img = cv2.imread('sharping.tif',0)
mask=(2)*np.array([[0,1,0],[1,-4,1],[0, 1, 0]],dtype='float32')
mask2=(2)*np.array([[1,1,1],[1,-8,1],[1, 1, 1]],dtype='float32')
out1=cv2.filter2D(img,-1,mask)
out2=cv2.filter2D(img,-1,mask2)
33
title = ["orignal img-EC020","filtered output","filtered 8 "]
image=[img,out1,out2]
for i in range(3):

plt.subplot(1,3,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

IV. Apply sobel and prewait mask on digital image to detect edges.

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

img = cv2.imread('sob_pre.tif',0)
mask_drashti=np.array([[1,2,1],[0,0,0],[-1, -2, -1]],dtype='float32') #horizontal sobel
mask2_drashti=np.array([[1,1,1],[0,0,0],[-1, -1, -1]],dtype='float32') # horizontal prewait
mask3_drashti=np.array([[-1,0,1],[-2,0,2],[-1, 0, 1]],dtype='float32') #vertical sobel
mask4_drashti=np.array([[-1,0,1],[-1,0,1],[-1,0, 1]],dtype='float32') # vertical prewait
out1=cv2.filter2D(img,-1,mask)
out2=cv2.filter2D(img,-1,mask2)
out3=cv2.filter2D(img,-1,mask3)
out4=cv2.filter2D(img,-1,mask4)
titles = ["original img-EC020","horizontal sobel","horizontal prewait","vertical
sobel","vertical prewait"]
image=[img,out1,out2,out3,out4]
for i in range(5):
plt.subplot(2, 3, i+1)
plt.imshow(image[i], cmap='gray')
plt.title(titles[i])

34
plt.xticks([])
plt.yticks([])
plt.show()

Result:

CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
___________________________________________________________________________________________________

35
EXPERIMENT – 6
IMAGE RESTORATION

OBJECTIVE:
I. Implement the Alpha trimmed Order Statistic Restoration filter.
II. Implement the Following Mean Restoration filters: Arithmetic, Contra Harmonic.

SAMPLE PROGRAM:

I. Implement the Alpha trimmed Order Statistic Restoration filter.


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

def trimmeanval(arr, d):


n = len(arr)
k = int(d/2)
return np.mean(arr[k:n-k])

img1 = cv2.imread('test.tif', 0)

max_val=np.max(img1);
print(max_val);

img2=(img1/max_val); # Normalization

a=0;
b=0.05;
(nr,nc) = img1.shape

x=a+(b*np.random.normal(a,b,(nr,nc))); # Gaussian Distribution with mean (a) and


variance (b)
y=a+((b-a)*np.random.rand(nr,nc)); # Uniform Distribution

img_guassian=(img2+x)*max_val;
img_guassian_uint8 = np.array(img_guassian,dtype=np.uint8)

# Adding Salt&Pepper Noise


prob=0.05;

output2 = np.zeros((nr,nc),dtype = 'uint8');


thres=1-prob;

for i in range(nr):
for j in range(nc):
rdn=random.random()
if rdn < prob:

36
output2[i][j]=0;
elif rdn > thres:
output2[i][j]=255;
# else:
# output2[i][j]=img_guassian[i][j];

img_guassian_uint8 = np.array(img_guassian,dtype=np.uint8);

###### Alpha Trimmed Filter


img_noise=img_guassian+output2;
(nr,nc) = img_noise.shape # to access row and column of image
print('No. of Row: ',nr)
print('No. of Column: ', nc)

recovred_image=np.zeros((nr,nc),dtype='uint8');
ary=np.zeros(9,dtype='uint8');
ary1=np.zeros(9,dtype='uint8');
d=6
for i in range(1,nr-1):
for j in range(1,nc-1):
temp=0;
for x in range(i-1,i+2):
for y in range(j-1,j+2):
ary[temp] = img_noise[x,y]
temp +=1
ary.sort()
ary1 = ary
recovred_image[i][j] = trimmeanval(ary1,d);

titles = ['EC020-Original Image', '(Gaussian + Salt & Pepper)', 'Recoverd Image']


images = [img1, img_noise,recovred_image]

for k in range(3):
plt.subplot(2, 3, k+1)
plt.imshow(images[k],cmap='gray')
plt.title(titles[k])
plt.xticks([])
plt.yticks([])
histr_original = cv2.calcHist([img1],[0],None,[256],[0,258])
histr_Noisy_Gaussian = cv2.calcHist([np.uint8(img_noise)],[0],None,[256],[0,258])
histr_recovred_image = cv2.calcHist([recovred_image],[0],None,[256],[0,258])
plt.subplot(2,3,4)
plt.plot(histr_original)
plt.title('HistogramOfTestPattern')
plt.subplot(2,3,5)
plt.plot(histr_Noisy_Gaussian)
plt.title('Gaussian+Salt & Pepper')
plt.subplot(2,3,6)
plt.plot(histr_recovred_image)
plt.title('Histogram of Recovred Image')
37
plt.show()

Result:

II. Implement the Following Mean Restoration filters: Arithmetic, Contra Harmonic.
import cv2
import numpy as np
import matplotlib.pyplot as plt
import random

img1 = cv2.imread('test2.tif', 0)

max_val=np.max(img1);
print(max_val);

img2=(img1/max_val); # Normalization

a=0;
b=0.3;
(nr,nc) = img1.shape

x=a+(b*np.random.normal(a,b,(nr,nc))); # Gaussian Distribution with mean (a) and


variance (b)
y=a+((b-a)*np.random.rand(nr,nc)); # Uniform Distribution

img_guassian=(img2+x)*max_val;
img_guassian_uint8 = np.array(img_guassian,dtype=np.uint8)
###### Arithmetic Mean Filter
filterSize = 3
k1 = np.array(np.ones((filterSize, filterSize), np.float32))/(filterSize * filterSize) #average
filter
print(k1)
38
output1 = cv2.filter2D(img_guassian, -1, k1)

# Adding Salt&Pepper Noise


prob=0.05;

R = np.zeros((nr,nc),dtype = 'uint8');
thres=1-prob;

for i in range(nr):
for j in range(nc):
rdn=random.random()
if rdn < prob:
R[i][j]=0;
# elif rdn > thres:
# R[i][j]=255;
else:
R[i][j]=img1[i][j];

img_noise=R;

###### Contra-Harmonic Filter


(nr,nc) = img_noise.shape # to access row and column of image
print('No. of Row: ',nr)
print('No. of Column: ', nc)
output=np.zeros((nr,nc),dtype='uint8');
Q=1.5;
for i in range(1,nr-1,1):
for j in range(1,nc-1,1):
num=0;denom=0;
for x in range(i-1,i+2):
for y in range(j-1,j+2):
num = num + (pow(img_noise[x][y],(Q+1)))
denom = denom + (pow(img_noise[x][y],Q))
if denom != 0:
output[i][j]= np.uint8(num / denom);

titles=["Original Image-EC020","Noisy Image","Arithmetic Mean Filter","Original


Image-EC020","Noisy Image","Contra-Harmonic Filter"]
images=[img1,img_guassian,output1,img1,img_noise,output]

for k in range(6):
plt.subplot(2, 3, k+1)
plt.imshow(images[k], cmap='gray')
plt.title(titles[k])
plt.xticks([])
plt.yticks([])

# Display the images


plt.tight_layout()
plt.show()
39
Result:

ASSIGNMENT:

I. Implement the Following Order Statistic Restoration filters: Median, Max, Min, Mid-Point.
import cv2
import numpy as np
import matplotlib.pyplot as plt

# Function to apply Max filter


def max_filter(image, kernel_size=3):
return cv2.dilate(image, np.ones((kernel_size, kernel_size), np.uint8))

# Function to apply Min filter


def min_filter(image, kernel_size=3):
return cv2.erode(image, np.ones((kernel_size, kernel_size), np.uint8))

# Function to apply Median filter


def median_filter(image, kernel_size=3):
return cv2.medianBlur(image, kernel_size)

# Function to apply Mid-point filter


def midpoint_filter(image, kernel_size=3):
# Get the min and max filters
max_img = max_filter(image, kernel_size)
40
min_img = min_filter(image, kernel_size)

# Mid-point filter = (Max + Min) / 2


midpoint_img = (max_img.astype(np.float32) + min_img.astype(np.float32)) / 2
return midpoint_img.astype('uint8')

# Read the grayscale image


img = cv2.imread('ckt-board-saltpep-prob.pt05.tif', 0)

# Apply the filters


median_filtered = median_filter(img)
max_filtered = max_filter(img)
min_filtered = min_filter(img)
midpoint_filtered = midpoint_filter(img)

# List of filtered images


filtered_images = [img, median_filtered, max_filtered, min_filtered, midpoint_filtered]

# Titles for the plots


titles = ["Original Image-EC020", "Median Filter", "Max Filter", "Min Filter", "Mid-
Point Filter"]

# Plot the images in a 2x3 grid


plt.figure(figsize=(10, 6))
for i in range(5):
plt.subplot(2, 3, i+1)
plt.imshow(filtered_images[i], cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])

# Show the plot


plt.tight_layout()
plt.show()

Result:

41
II. Implement the Following Mean Restoration filters: Geometric, Harmonic.

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

# Load the image in grayscale


img = cv2.imread('geo_filter.tif', 0)

(M, N) = img.shape # M: number of rows, N: number of columns


out1 = np.ones((M, N), dtype='float32')
out = np.ones((M, N), dtype='float32')
ksize = 9 # Kernel size
padsize = int((ksize - 1) / 2)

for i in range(0, M-1 ):


for j in range(0, N-1 ):
for k in range(1,padsize):
out1[:,j]=img[:,j]
for l in range(1,padsize):
out1[i,:]=img[i,:]
for i in range(padsize, M - padsize):
for j in range(padsize, N - padsize):

for x in range(-padsize, padsize + 1):

out[i][j] *= img[i + x][j ]


out[i][j] = out[i][j] ** (1 / (ksize*2))
for y in range(-padsize, padsize + 1):
out1[i][j] *= img[i][j+y]

out1[i][j] = out1[i][j] ** (1 / (ksize*2))


out1[i][j]=out1[i][j]*out[i][j]

42
mask=(1/(ksize*ksize))*(np.ones((ksize,ksize),dtype='float32'))
out2=cv2.filter2D(img,-1,mask)

###### Contra-Harmonic Filter


output=np.zeros((M,N),dtype='uint8');
Q=-1.5;
for i in range(1,M-1,1):
for j in range(1,N-1,1):
num=0;denom=0;
for x in range(i-1,i+2):
for y in range(j-1,j+2):
num = num + (pow(img[x][y],(Q+1)))
denom = denom + (pow(img[x][y],Q))
if denom != 0:
output[i][j]= np.uint8(num / denom);

image = [img, out1,out2,output]


title = ["Original Image-EC020", "Geometric Mean Filter","arithmetic Mean Filter","Harmonic
Mean Filter"]

for i in range(4):
plt.subplot(2, 2, i + 1)
plt.imshow(image[i], cmap='gray')
plt.title(title[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

43
III. W.A.P. to add salt & pepper noise in the original image also plot the histogram of the
same.

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

img1 = cv2.imread('test.tif', 0)

max_val=np.max(img1);
print('Maximum Intensity in Original Image:',max_val);

prob=0.05;
(nr,nc) = img1.shape;

output = np.zeros((nr,nc),dtype = 'uint8');


thres=1-prob;

for i in range(nr):
for j in range(nc):
rdn=random.random()
if rdn < prob:
output[i][j]=0;
elif rdn > thres:
output[i][j]=255;
else:
output[i][j]=img1[i][j];

max_val=np.max(output);
print('Maximum Intensity in Noisy Image:',max_val);
titles = ['Original Image-EC020', 'Noisy Image (Salt & Pepper)']
images = [img1, output]

for k in range(2):
plt.subplot(2, 2, k+1)
plt.imshow(images[k],cmap='gray')
plt.title(titles[k])
plt.xticks([])
plt.yticks([])
histr_original = cv2.calcHist([img1],[0],None,[256],[0,258])
histr_Noisy_SP = cv2.calcHist([output],[0],None,[256],[0,258])

44
plt.subplot(2,2,3)
plt.plot(histr_original)
plt.title('Histogram Pattern')
plt.subplot(2,2,4)
plt.plot(histr_Noisy_SP)
plt.title('Histogram of (Salt & Pepper)')

plt.show()

Result:

CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
___________________________________________________________________________________________________

45
EXPERIMENT – 7
COLOR IMAGE PROCESSING
OBJECTIVE:
I. Split and merge the R, G, B component from the color image.
II. Observe effect saturation of red, green and blue color component in the blank image.
III. Convert the RGB color Model into HSI Color Model.

SAMPLE PROGRAM:

I. Observe effect saturation of red, green and blue color component in the blank image.

import cv2
import numpy as np

def emptyFunction():
pass

def main():
img1 = np.zeros((512, 512, 3), np.uint8)
windowName = 'OpenCV BGR Color Palette'
cv2.namedWindow(windowName)

cv2.createTrackbar('B', windowName, 0, 255, emptyFunction)


cv2.createTrackbar('G', windowName, 0, 255, emptyFunction)
cv2.createTrackbar('R', windowName, 0, 255, emptyFunction)

while(True):
cv2.imshow(windowName, img1)
cv2.waitKey(0)
if cv2.waitKey(1) == 27: # ASCII Code for the ESC key

break

blue = cv2.getTrackbarPos('B', windowName)


green = cv2.getTrackbarPos('G', windowName)
red = cv2.getTrackbarPos('R', windowName)

46
img1[:] = [blue, green, red]
print (blue, green, red)

cv2.destroyAllWindows()

if __name__ == "__main__":
main()
Result:

47
II. Split and merge the R, G, B component from the color image.

import cv2
import matplotlib.pyplot as plt
#img1 = cv2.imread(‘index.jpg’,1)

img_drashti = cv2.imread("color.tif",1)
cv2.imshow('Original Color Image',img_drashti)

[b,g,r] = cv2.split(img_drashti)

48
rgb_img = cv2.merge([b,g,r])

images=[img_drashti,b,g,r,rgb_img]
titles=['Original Color Image-EC020','Blue Component-EC020','Green Component-EC020','Red
Component-EC020','Color Image-EC020']

for i in range (5):


plt.subplot(2,3,i+1)
plt.imshow(images[i])
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

III. Convert the RGB color Model into HSI Color Model.

49
import cv2
import numpy as np
import math

def RGB_TO_HSI(img):

with np.errstate(divide='ignore', invalid='ignore'):

#Load image with 32 bit floats as variable type


bgr = np.float32(img)/255

#Separate color channels


blue = bgr[:,:,0]
green = bgr[:,:,1]
red = bgr[:,:,2]

#Calculate Intensity
def calc_intensity(red, blue, green):
return np.divide(blue + green + red, 3)

#Calculate Saturation
def calc_saturation(red, blue, green):
minimum = np.minimum(np.minimum(red, green), blue)
saturation = 1 - (3 / (red + green + blue + 0.001) * minimum)

return saturation

#Calculate Hue
def calc_hue(red, blue, green):
hue = np.copy(red)

for i in range(0, blue.shape[0]):


for j in range(0, blue.shape[1]):
hue[i][j] = 0.5 * ((red[i][j] - green[i][j]) + (red[i][j] - blue[i][j])) / \
math.sqrt((red[i][j] - green[i][j])**2 +
((red[i][j] - blue[i][j]) * (green[i][j] - blue[i][j])))
hue[i][j] = math.acos(hue[i][j])

if blue[i][j] <= green[i][j]:


hue[i][j] = hue[i][j]
50
else:
hue[i][j] = ((360 * math.pi) / 180.0) - hue[i][j]

return hue

#Merge channels into picture and return image


hsi = cv2.merge((calc_hue(red, blue, green), calc_saturation(red, blue, green),
calc_intensity(red, blue, green)))
return hsi

import cv2
import converter

# Import picture & create HSI copy using algorithm


#img = cv2.imread('sourceImg.jpg', 1)
img = cv2.imread('index.jpg', 1);
img=cv2.resize(img,(300,300),cv2. INTER_AREA);
cv2.imshow('Org Image', img)
cv2.waitKey(0)

hsi = converter.RGB_TO_HSI(img)

# Display HSV Image


cv2.imshow('HSI Image', hsi)
cv2.waitKey(0)
# The three value channels

cv2.imshow('H Channel', hsi[:, :, 0])


cv2.waitKey(0)

cv2.imshow('S Channel', hsi[:, :, 1])


cv2.waitKey(0)

cv2.imshow('I Channel', hsi[:, :, 2])

# Wait for a key press and then terminate the program


cv2.waitKey(0)
cv2.destroyAllWindows()

51
Result:

MODIFICATIONS:
I. Generate the following Color Images having dimension 512*512.

52
Pure RED Color, Pure GREEN Color, Pure BLUE Color, Pure WHITE Color, Pure BLACK
Color

import cv2
import matplotlib.pyplot as plt
import numpy as np
import math as m
b = (np.ones((512,512),dtype = 'uint8'))*255
r = (np.ones((512,512),dtype = 'uint8'))*255
g = (np.ones((512,512),dtype = 'uint8'))*255
rgb_img = cv2.merge([b,g,r])
cv2.imshow('Color Image-EC020', rgb_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result:

53
CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_____
54
EXPERIMENT –08

IMAGE SEGMENTATION & MORPHOLOGICAL OPERATION

Objective:

● To find optimum threshold value by maximizing between class variance.


● Perform erosion operation on binary image with various structuring elements.
● Perform dilation operation on binary image with various structuring elements.
● Illustrating morphological open by erosion followed by dilation.
● Illustrating morphological close by dilation followed by erosion.

SAMPLE PROGRAM:

I. To find optimum threshold value by maximizing between class variance.


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

img = cv2.imread('coins.png',0)
cv2.imshow("original image-EC020",img)
cv2.waitKey(0);
cv2.destroyAllWindows();
(M,N)=img.shape
# cv2.imshow("out1",img)
# cv2.waitKey(0);
# cv2.destroyAllWindows();
a=np.zeros(256,dtype='uint8')

# for j in range(M):
# for k in range(N):
# i1=img[j][k]

# a[i1]=a[i1]+1;

# print(a)
# plt.plot(a)
#cv2.calcHist(images, channels, mask, histSize, ranges) for histo.
for i in range(M):
for j in range(N):
55
if(img[i][j] <= 95):
img[i][j]=0;
else:
img[i][j]=255;

cv2.imshow("after seg.-EC020",img)
cv2.waitKey(0);
cv2.destroyAllWindows();
Result:

ii. Perform erosion operation on binary image with various structuring elements.

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

img = cv2.imread('seg_mor.tif',0)

drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')
drashti_se1=np.array([[1,1,1]],dtype='float32')
drashti_se2=np.array([[1],[1],[1]],dtype='float32')
drashti_se3=np.array([[0,1,0],[1,1,1],[0,1,0]],dtype='uint8')
drashti_se4=np.array([[0,0,1],[0,1,0],[1,0,0]],dtype='uint8')
drashti_se5=np.ones((15,15),dtype='float32')
output=cv2.erode(img, drashti_se, iterations=5)
output1=cv2.erode(img, drashti_se1, iterations=5)
output2=cv2.erode(img, drashti_se2, iterations=5)
output3=cv2.erode(img, drashti_se3, iterations=5)
56
output4=cv2.erode(img, drashti_se4, iterations=5)
output5=cv2.erode(img, drashti_se5, iterations=5)

image = [ img,output,output1,output2,output3,output4,output5]
titles=[orignal img-EC020", "erosion","erosion","erosion","erosion","erosion","erosion"]
for i in range(7):
plt.subplot(2,4,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

iii. Perform dilation operation on binary image with various structuring elements.
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('seg_mor.tif',0)

drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')
drashti_se1=np.array([[1,1,1]],dtype='float32')
drashti_se2=np.array([[1],[1],[1]],dtype='float32')
drashti_se3=np.array([[0,1,0],[1,1,1],[0,1,0]],dtype='uint8')
drashti_se4=np.array([[0,0,1],[0,1,0],[1,0,0]],dtype='uint8')
drashti_se5=np.ones((15,15),dtype='float32')

#for dilte
output=cv2.dilate(img, drashti_se)

57
output1=cv2.dilate(img, drashti_se1)
output2=cv2.dilate(img, drashti_se2)
output3=cv2.dilate(img, drashti_se3)
output4=cv2.dilate(img, drashti_se4)
output5=cv2.dilate(img, drashti_se5)

image = [ img,output,output1,output2,output3,output4,output5]
titles = ["orignal img-EC020", "dilate","dilate","dilate","dilate","dilate","dilate"]
for i in range(7):
plt.subplot(2,4,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()
Result:

IV. Ilustrating morphological open by erosion followed by dilation.


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

img = cv2.imread('seg_mor.tif',0)

drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')

img_open = cv2.morphologyEx(img, cv2.MORPH_OPEN, drashti_se)


image=[img,img_open]
titles = ["original img-EC020", "after opening op."]
for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i],cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
58
plt.show()

Result:

v. Illustrating morphological close by dilation followed by erosion.


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

img = cv2.imread('seg_mor.tif',0)

drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')

img_close = cv2.morphologyEx(img, cv2.MORPH_CLOSE, drashti_se)


image=[img,img_close]
titles = ["original img-EC020", "after closing op."]
for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i],cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

59
MODIFICATIONS:

(i) Perform dilation operation on binary image with various structuring elements.
Hint: in-built function is: dilate
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('seg_mor.tif',0)

drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')
drashti_se1=np.array([[1,1,1]],dtype='float32')
drashti_se2=np.array([[1],[1],[1]],dtype='float32')
drashti_se3=np.array([[0,1,0],[1,1,1],[0,1,0]],dtype='uint8')
drashti_se4=np.array([[0,0,1],[0,1,0],[1,0,0]],dtype='uint8')
drashti_se5=np.ones((15,15),dtype='float32')

#for dilte
output=cv2.dilate(img, drashti_se)
output1=cv2.dilate(img, drashti_se1)
output2=cv2.dilate(img, drashti_se2)
output3=cv2.dilate(img, drashti_se3)
output4=cv2.dilate(img, drashti_se4)
output5=cv2.dilate(img, drashti_se5)

image = [ img,output,output1,output2,output3,output4,output5]
titles = ["orignal img-EC020", "dilate","dilate","dilate","dilate","dilate","dilate"]
for i in range(7):
plt.subplot(2,4,i+1)
plt.imshow(image[i], cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

60
(ii) Illustrating morphological open by erosion followed by dilation.
Hint: in-built function is: img_open = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('seg_mor.tif',0)
drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')
img_open = cv2.morphologyEx(img, cv2.MORPH_OPEN, drashti_se)
image=[img,img_open]
titles = ["original img-EC020", "after opening op."]
for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i],cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

(iii) Illustrating morphological open by dilation followed by erosion.


Hint: in-built function is: img_close = cv2.morphologyEx(img, cv2.MORPH_CLOSE,
kernel)
import cv2
import numpy as np
import matplotlib.pyplot as plt

61
img = cv2.imread('seg_mor.tif',0)

drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')

img_close = cv2.morphologyEx(img, cv2.MORPH_CLOSE, drashti_se)


image=[img,img_close]
titles = ["original img-EC020", "after closing op."]
for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(image[i],cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()

Result:

ASSIGNMENTS:

I. Apply (i) different structuring elements, (ii) different iterations, and write your
observations.

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

path="seg_mor.tif"

img=cv.imread(path,0)
print(img.dtype)
(m,n)=img.shape
print(m,n)
struct_element=np.mat([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')
images = [img] + [cv.erode(img, struct_element, iterations=i) for i in [1, 5, 10]]
titles = ["Original-EC020", "Eroded iter=1", "Eroded itern=5", "Eroded iter=10"]

62
for i in range(4):
plt.subplot(1, 4, i + 1)
plt.imshow(images[i],cmap='gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])

plt.show()
Result:

II. Modify the program without using in-built erode and dilate functions.
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

path="seg_mor.tif"

img=cv.imread(path,0)
def erosion(img, kernel):
kernel = np.array(kernel, dtype='uint8')
(nr, nc) = img.shape
img2 = np.zeros((nr, nc), dtype='uint8')
kernel_size = kernel.shape[0]
offset = kernel_size // 2

for i in range(offset, nr - offset):


for j in range(offset, nc - offset):
temp = img[i - offset:i + offset + 1, j - offset:j + offset + 1]
product = temp * kernel
img2[i, j] = np.min(product)
return img2

def dilation(img, kernel):


kernel = np.array(kernel, dtype='uint8')
(nr, nc) = img.shape
img2 = np.zeros((nr, nc), dtype='uint8')

63
kernel_size = kernel.shape[0]
offset = kernel_size // 2

for i in range(offset, nr - offset):


for j in range(offset, nc - offset):
temp = img[i - offset:i + offset + 1, j - offset:j + offset + 1]
product = temp * kernel
img2[i, j] = np.max(product)
return img2
kernel=np.ones((3,3),dtype='uint8')
img2=erosion(img,kernel)
img3=cv.erode(img,kernel,iterations=1);
titles1=['Original-EC020','Erosion', 'Erosion with function']
images1=[img, img2, img3]
for i in range(3):
plt.subplot(2,3,i+1)
plt.imshow(images1[i],cmap='gray')
plt.title(titles1[i])
plt.xticks([])
plt.yticks([])
img4=dilation(img,kernel)
img5=cv.dilate(img,kernel,iterations=1);
titles2=['Original-EC020','Dilation', 'Dilation with inbuilt function']
images2=[img, img4, img5]
for i in range(3):
plt.subplot(2,3,i+4)
plt.imshow(images2[i],cmap='gray')
plt.title(titles2[i])
plt.xticks([])
plt.yticks([])

plt.show()

Result:

64
III. Modify the open and close programs using erosion and dilation functions.
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

path="seg_mor.tif"

img=cv.imread(path,0)
def erosion(img, kernel):
kernel = np.array(kernel, dtype='uint8')
(nr, nc) = img.shape
img2 = np.zeros((nr, nc), dtype='uint8')
kernel_size = kernel.shape[0]
offset = kernel_size // 2
for i in range(offset, nr - offset):
for j in range(offset, nc - offset):
temp = img[i - offset:i + offset + 1, j - offset:j + offset + 1]
product = temp * kernel
img2[i, j] = np.min(product)
return img2

def dilation(img, kernel):


kernel = np.array(kernel, dtype='uint8')
(nr, nc) = img.shape
img2 = np.zeros((nr, nc), dtype='uint8')
kernel_size = kernel.shape[0]
offset = kernel_size // 2
for i in range(offset, nr - offset):
for j in range(offset, nc - offset):

65
temp = img[i - offset:i + offset + 1, j - offset:j + offset + 1]
product = temp * kernel
img2[i, j] = np.max(product)
return img2

def opening(img, kernel):


return dilation(erosion(img, kernel), kernel)
def closing(img, kernel):
return erosion(dilation(img, kernel), kernel)

kernel=np.ones((3,3),dtype='uint8')
img2=opening(img,kernel)
img3=cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
titles1=['Original Image-EC020', 'Opening(Custom)', 'Opening (Inbuilt)']
images1=[img, img2, img3]

for i in range(3):
plt.subplot(2,3,i+1)
plt.imshow(images1[i],cmap='gray')
plt.title(titles1[i])
plt.xticks([])
plt.yticks([])

img4=closing(img,kernel)
img5=cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
titles2=['Original Image-EC020', 'Closing(Custom)', 'Closing (Inbuilt)']
images2=[img, img4, img5]

for i in range(3):
plt.subplot(2,3,i+4)
plt.imshow(images2[i],cmap='gray')
plt.title(titles2[i])
plt.xticks([])
plt.yticks([])

plt.show()

Result:

66
CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_____

67
EXPERIMENT –09

IMAGE CLASSIFICATION USING K-MEANS CLUSTERING ALGORITHM

OBJECTIVE: To implement image classification using the K-Means clustering algorithm, which is an
unsupervised learning technique.
SAMPLE PROGRAM:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
np.random.seed(5)
#generate 2D random data for three clusters and represent them
def generate_data():
np.random.seed(5)
x1 = np.random.standard_normal((100,2))*0.2+np.ones((100,2))
x2 = np.random.standard_normal((100,2))*0.5-np.ones((100,2))
x3 = np.random.standard_normal((100,2))*0.4-2*np.ones((100,2))+5
X = np.concatenate((x1,x2,x3),axis=0)
print(x1)
return X
# plt.plot(X[:,0],X[:,1],'k.')
# plt.show()
#generate the k=3 initial centroids with the function
n=4
X = generate_data()
k_means = KMeans(n_clusters=n)
model = k_means.fit(X)
centroids = k_means.cluster_centers_
labels= k_means.labels_
plt.figure()
plt.plot(X[labels==0,0],X[labels==0,1],'r.', label='cluster 1')
plt.plot(X[labels==1,0],X[labels==1,1],'b.', label='cluster 2')
plt.plot(X[labels==2,0],X[labels==2,1],'g.', label='cluster 3')
plt.plot(centroids[:,0],centroids[:,1],'mo',markersize=8, label='centroids')
plt.legend(loc='best')
68
plt.show()

Result:

MODIFICATIONS:
I. Generate different number of clusters and try with different number of centroids. Write your
observations.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

def generate_data():
np.random.seed(5)
x1 = np.random.standard_normal((100,2))*0.2+np.ones((100,2))
x2 = np.random.standard_normal((100,2))*0.5-np.ones((100,2))
x3 = np.random.standard_normal((100,2))*0.4-2*np.ones((100,2))+5
X = np.concatenate((x1, x2, x3), axis=0)
return X

def run_kmeans(X, num_clusters):


k_means = KMeans(n_clusters=num_clusters, random_state=42)
model = k_means.fit(X)
centroids = k_means.cluster_centers_
labels = k_means.labels_

plt.figure()
colors = ['r.', 'b.', 'g.', 'y.', 'c.', 'm.', 'k.']

69
for i in range(num_clusters):
plt.plot(X[labels == i, 0], X[labels == i, 1], colors[i % len(colors)], label=f'Cluster {i+1}')

plt.plot(centroids[:, 0], centroids[:, 1], 'mo', markersize=8, label='Centroids')


plt.legend(loc='best')
plt.title(f'EC021_K-means with {num_clusters} clusters')
plt.show()

X = generate_data()

for n_clusters in [2, 3, 4, 5]:


run_kmeans(X, n_clusters)

Result:

70
CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_____

Date: ____________
EXPERIMENT – 10
Image Classification Using K-Means Clustering Algorithm
OBJECTIVE:
1) To evaluate weight for different logic gates using perceptron algorithm.
2) To apply gradient decent algorithm.

Sample programs:

Objective – I:
71
To evaluate weight for OR logic gate using perceptron algorithm.
import numpy as np
atributes = np.array([ [0, 0], [0, 1], [1, 0], [1, 1]])
labels = np.array([0, 1, 1, 1])
w = [0.1, 0.1]
threshold = 0.7
bias = 0
alpha = 0.05
epoch = 50
print("EC020")
print("learning rate: ", alpha,", threshold: ", threshold)
for i in range(0, epoch):
print("epoch ", i+1)
global_delta = 0
for j in range(len(atributes)):
actual = labels[j]
sum = atributes[j][0]*w[0] + atributes[j][1]*w[1] + bias
if sum > threshold:
predicted = 1
else:
predicted = 0
delta = actual - predicted
global_delta = global_delta + abs(delta)
for k in range(0, 2):
w[k] = w[k] + delta * alpha
print(atributes[j][0]," ", labels, " ", atributes[j][1], " -> actual: ", actual, ", predicted:
",predicted, " (w: ",w[0],")")
if global_delta == 0:
break
print("------------------------------")

Result:

72
MODIFICATION:
1) To evaluate weight for AND logic gate using perceptron algorithm.

import numpy as np
atributes = np.array([ [0, 0], [0, 1], [1, 0], [1, 1]])
labels = np.array([0, 0, 0, 1])
w = [0.1, 0.1]
threshold = 0.7
bias = 0
alpha = 0.5
epoch = 50
print("EC020")
print("learning rate: ", alpha,", threshold: ", threshold)
for i in range(0, epoch):
print("epoch ", i+1)
global_delta = 0
for j in range(len(atributes)):
actual = labels[j]
sum = atributes[j][0]*w[0] + atributes[j][1]*w[1] + bias
if sum > threshold:
predicted = 1
else:
predicted = 0
delta = actual - predicted
73
global_delta = global_delta + abs(delta)
for k in range(0, 2):
w[k] = w[k] + delta * alpha
print(atributes[j][0]," ", labels, " ", atributes[j][1], " -> actual: ", actual, ", predicted:
",predicted, " (w: ",w[0],")")
if global_delta == 0:
break
print("------------------------------")

Result:

2)To evaluate weight for XOR logic gate using perceptron algorithm,
Result:
The perceptron algorithm is not suitable for learning the XOR logic gate because XOR is not linearly
separable. In other words, there is no single line (or hyperplane in higher dimensions) that can separate
the classes correctly. For the XOR gate, the input-output pairs are as follows:
• Input: [0, 0] → Output: 0
• Input: [0, 1] → Output: 1
• Input: [1, 0] → Output: 1
• Input: [1, 1] → Output: 0
74
Observations:
1. Non-Linearity: Unlike AND and OR gates, the XOR gate outputs 1 for inputs that are different. This
creates a situation where the points cannot be separated by a single linear boundary.
2. Inability to Converge: When trying to train a perceptron on the XOR data, the algorithm will fail to
converge to a solution. It will not be able to correctly classify the data points.
3. Need for Multi-Layer Networks: To successfully model the XOR function, you need a multi-layer
neural network (at least one hidden layer) which can create non-linear decision boundaries. This is why
perceptrons alone (which are single-layer networks) cannot solve problems like XOR.

3) To evaluate weight for NOT logic gate using perceptron algorithm,


import numpy as np
atributes = np.array([[0], [1]])
labels = np.array([1, 0])

w = [1]
threshold = 0.5
bias = 0
alpha = 0.2
epoch = 5

print("21ECUOG077 W = [1]")
print("Learning rate: ", alpha, ", Threshold: ", threshold)
for i in range(0, epoch):
print("Epoch ", i + 1)
global_delta = 0
for j in range(len(atributes)):
actual = labels[j]
sum = atributes[j][0] * w[0] + bias
if sum > threshold:
predicted = 1
else:
predicted = 0

delta = actual - predicted


global_delta += abs(delta)

w[0] = w[0] + delta * alpha

print(f"Input: {atributes[j][0]}, Actual: {actual}, Predicted: {predicted}, (W: {w[0]})")

if global_delta == 0:
break

print("------------------------------")

Result :

75
Objective – II:

To apply gradient decent algorithm for y = x^2

76
from numpy import asarray
from numpy import arange
from numpy.random import rand
from matplotlib import pyplot

def objective(x):
return x**2.0

def derivative(x):
return x * 2.0

def gradient_descent(objective, derivative, bounds, n_iter, step_size):


solutions, scores = list(), list()
#solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
solution=0.7862
for i in range(n_iter):
gradient = derivative(solution)
solution = solution - step_size * gradient
solution_eval = objective(solution)
solutions.append(solution)
scores.append(solution_eval)
print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
return [solutions, scores]

bounds = asarray([[-1.0, 1.0]])


n_iter = 10
step_size = 0.01
solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)
inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
results = objective(inputs)
pyplot.plot(inputs, results)
pyplot.plot(solutions, scores, '.-', color='red')
pyplot.title('EC020 - ITR=10 - STEPSIZE=0.01')
pyplot.show()

Result:

77
ASSIGNMENTS:

1) To apply gradient decent algorithm for y = 2(x^2)

from numpy import asarray


from numpy import arange
from numpy.random import rand
from matplotlib import pyplot

def objective(x):
return 2*x**2.0

def derivative(x):
return x * 4.0

def gradient_descent(objective, derivative, bounds, n_iter, step_size):


solutions, scores = list(), list()
#solution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
solution = 0.7862
for i in range(n_iter):
gradient = derivative(solution)
solution = solution - step_size * gradient
solution_eval = objective(solution)
solutions.append(solution)
scores.append(solution_eval)
print('>%d f(%s) = %.5f' % (i, solution, solution_eval))
return [solutions, scores]

bounds = asarray([[-1.0, 1.0]])


n_iter = 15
step_size = 0.01
solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)
inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)
results = objective(inputs)
pyplot.title('EC020 - ITR=15 - STEPSIZE=0.01')
pyplot.plot(inputs, results)
pyplot.plot(solutions, scores, '.-', color='red')
78
pyplot.show()

Result:

CONCLUSION:
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_

79
supplementary Assignment:

Write a python program to obtain a recovered image by altering all the bits of the bit plane (Black to White & White to
Black) for an image shown in image.

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

# Load the image in grayscale


img = cv2.imread('img_6.tif', 0) # Replace 'image.tif' with your actual image file

# Invert all the bits in the image


recovered_img = cv2.bitwise_not(img)

# Plot original and recovered images side by side


plt.figure(figsize=(10, 5))

# Display original image


plt.subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title('Original Image')
plt.xticks([])
plt.yticks([])

# Display recovered (bit-flipped) image


plt.subplot(1, 2, 2)
plt.imshow(recovered_img, cmap='gray')
plt.title('Recovered Image (Bit-flipped)')
plt.xticks([])
plt.yticks([])

plt.show()

Result:
80
81

You might also like