DRASHTI_CVML
DRASHTI_CVML
B. Tech.
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.
DATE
PAGE
NO. EXPERIMENT TITLE OF SIGN
NO.
EXPERIMENT
Basic Functions Of Image Processing With
1 OpenCV
1 3/7/2024
24/10/9/2
3 Contrast Enhancement Algorithms 11
0247/2024
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:
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
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:
img = cv2.imread('gray1.tif',0)
img1 = cv2.imread('gray3.tif',0)
img2 = cv2.imread('gray4.tif',0)
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];
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)
Result:
9
Average intensity of darker image = 118.7244873046875
avg. intensity of Average image = 0.881175875242331
avg. intensity of brighter image = 235.4876365565186
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)
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
SAMPLE PROGRAM:
#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
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:
import cv2
import numpy as np
import matplotlib.pyplot as plt
Result:
23
CONCLUSION:
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
_________________________________________________________________________________________________________________
___________________________________________________________________________________________________
24
EXPERIMENT – 5
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:
26
# Create a subplot for each filtered image
plt.figure(figsize=(12, 8))
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
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)
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
# 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)
Result:
30
II. Vary amount of noise and compare output of both filters.
import cv2
import numpy as np
import matplotlib.pyplot as plt
return noisy_img
31
# Different noise levels to be added (amount of noise)
noise_levels = [0.01, 0.05, 0.1] # Low, medium, and high noise
median_filtered.append(median_filtered_img)
avg_filtered.append(avg_filtered_img)
32
plt.title(f'Avg Filter (Noise={noise_amount})')
plt.xticks([])
plt.yticks([])
Result:
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:
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
img_guassian=(img2+x)*max_val;
img_guassian_uint8 = np.array(img_guassian,dtype=np.uint8)
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);
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);
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
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)
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;
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([])
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
Result:
41
II. Implement the Following Mean Restoration filters: Geometric, Harmonic.
import cv2
import numpy as np
import matplotlib.pyplot as plt
42
mask=(1/(ksize*ksize))*(np.ones((ksize,ksize),dtype='float32'))
out2=cv2.filter2D(img,-1,mask)
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;
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)
while(True):
cv2.imshow(windowName, img1)
cv2.waitKey(0)
if cv2.waitKey(1) == 27: # ASCII Code for the ESC key
break
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']
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):
#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)
return hue
import cv2
import converter
hsi = converter.RGB_TO_HSI(img)
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
Objective:
SAMPLE PROGRAM:
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:
img = cv2.imread('seg_mor.tif',0)
drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')
Result:
img = cv2.imread('seg_mor.tif',0)
drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')
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:
61
img = cv2.imread('seg_mor.tif',0)
drashti_se=np.array([[1,1,1],[1,1,1],[1,1,1]],dtype='float32')
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
63
kernel_size = kernel.shape[0]
offset = kernel_size // 2
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
65
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=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
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
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}')
X = generate_data()
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.
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
if global_delta == 0:
break
print("------------------------------")
Result :
75
Objective – II:
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
Result:
77
ASSIGNMENTS:
def objective(x):
return 2*x**2.0
def derivative(x):
return x * 4.0
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
plt.show()
Result:
80
81