Exp 4-7

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

10/5/23, 11:33 AM Untitled1

EXPERIMENT No 4:2D Discrete Cosine


Transform (DCT)
Aim: To find:

1. 2D DCT of a 4x4 image segment using matrix method


2. 2D DCT using standard equation for an image of size NxN
3. 2D DCT of the image saved in drive and verify the energy compaction property
Date:05/10/23

In [1]: import numpy as np


img_seg=np.array(([1,2,2,1],
[2,1,2,1],
[1,2,2,1],
[2,1,2,1]))
dct_matrix=np.array([[0.5, 0.5, 0.5, 0.5],
[0.65, 0.27, -0.27, -0.65],
[0.5, -0.5, -0.5, 0.5],
[0.27, -0.65, 0.65, -0.27]])
print(img_seg)
print(dct_matrix)

[[1 2 2 1]
[2 1 2 1]
[1 2 2 1]
[2 1 2 1]]
[[ 0.5 0.5 0.5 0.5 ]
[ 0.65 0.27 -0.27 -0.65]
[ 0.5 -0.5 -0.5 0.5 ]
[ 0.27 -0.65 0.65 -0.27]]

In [2]: #DCT using matix multiplicatin


dct_result=np.matmul(np.matmul(dct_matrix,img_seg),
dct_matrix.T)
print(np.round(dct_result,2))

[[ 6. 0.38 -1. 0.92]


[ 0. -0.14 -0.38 -0.35]
[ 0. 0. 0. 0. ]
[ 0. -0.35 -0.92 -0.85]]

In [ ]:

In [3]: from math import exp,pi,cos,sqrt


def alpha_fun(x,N):
if x==0:
return sqrt(1/N)
else:
return sqrt(2/N)
def dct_img(x):
row,col=len(x),len(x[0])
dct_eq=[]
for u in range(row):
temp=[]
for v in range(col):
temp_sum=0
for x in range(row):

localhost:8888/nbconvert/html/Untitled1.ipynb?download=false 1/4
10/5/23, 11:33 AM Untitled1
for y in range(col):
temp_sum+=img_seg[x][y]*cos((2*x+1)*u*pi/(2*row))*cos((2*y+1)*v
temp.append(alpha_fun(u,row)*alpha_fun(v,row)*temp_sum)
dct_eq.append(temp)
return np.round(np.array(dct_eq),2)
print(dct_img(img_seg))

[[ 6. 0.38 -1. 0.92]


[ 0. -0.15 -0.38 -0.35]
[-0. -0. 0. -0. ]
[-0. -0.35 -0.92 -0.85]]

In [4]: #DCT of an image and demonstration of energy compaction:

import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread('C:/Users/WT LAB/Desktop/BR/download.jpeg',cv2.IMREAD_GRAYSCALE)
img=cv2.resize(img,(550,350))
window='img'
print(img)
print("\n Input image\n")
cv2.imshow(window,img)
cv2.waitKey(0)
cv2.destroyAllWindows()

[[9 9 9 ... 9 9 9]
[9 9 9 ... 9 9 9]
[9 9 9 ... 9 9 9]
...
[7 7 7 ... 8 8 8]
[7 7 7 ... 9 9 9]
[7 7 7 ... 9 9 9]]

Input image

In [5]: img_float=np.float32(img)/255
dct=cv2.dct(img_float)
img_dct=np.clip(np.uint16(dct*255),0,255)
print("we see higher values(white pixels) nearer to[0,0], second half is almost nea
plt.imshow(img_dct,cmap='gray')

we see higher values(white pixels) nearer to[0,0], second half is almost nearer to
0 (black pixels)
<matplotlib.image.AxesImage at 0x24fe612a3d0>
Out[5]:

localhost:8888/nbconvert/html/Untitled1.ipynb?download=false 2/4
10/5/23, 11:33 AM Untitled1

In [14]: def zigzag_traversal(arr):


rows,cols=arr.shape
result=[]
for i in range(rows+cols-1):
temp=[]
for j in range(max(0,i-cols+1),min(i+1,rows)):
temp.append(arr[j,i-j])
result.append(temp)
return result
vals =zigzag_traversal(img_dct)
plot_y=[]
for k in vals:
plot_y.append(sum(k)/len(k))
print("Energy distribution visualized from dct result image")
print("Verifying energy compaction property.")
plt.plot(plot_y)
plt.xlabel("index of diagonal zigzag traversal")
plt.ylabel("pixel values from dct result image")
plt.show()

Energy distribution visualized from dct result image


Verifying energy compaction property.

localhost:8888/nbconvert/html/Untitled1.ipynb?download=false 3/4
10/5/23, 11:33 AM Untitled1

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

localhost:8888/nbconvert/html/Untitled1.ipynb?download=false 4/4
Assignment Question
Aim
Generate a 8X8 matrix. For each non overlapping block of size 2X2

• find the mean, median, maximum and minimum


• find the transpose
• check if two blocks are similar
• flatten the matrix by rowwise and columnwise
import numpy as np

matrix_8x8 = np.array([[ 1, 2, 3, 4, 5, 6, 7, 8],


[ 9, 10, 11, 12, 13, 14, 15, 16],
[17, 18, 19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30, 31, 32],
[33, 34, 35, 36, 37, 38, 39, 40],
[41, 42, 43, 44, 45, 46, 47, 48],
[49, 50, 51, 52, 53, 54, 55, 56],
[57, 58, 59, 60, 61, 62, 63, 64]])

submatrices = []
for i in range(0, 8, 2):
for j in range(0, 8, 2):
submatrix = np.array([[matrix_8x8[i][j], matrix_8x8[i][j +
1]],
[matrix_8x8[i + 1][j], matrix_8x8[i + 1]
[j + 1]]])
submatrices.append(submatrix)
for submatrix in submatrices:
print(submatrix)

[[ 1 2]
[ 9 10]]
[[ 3 4]
[11 12]]
[[ 5 6]
[13 14]]
[[ 7 8]
[15 16]]
[[17 18]
[25 26]]
[[19 20]
[27 28]]
[[21 22]
[29 30]]
[[23 24]
[31 32]]
[[33 34]
[41 42]]
[[35 36]
[43 44]]
[[37 38]
[45 46]]
[[39 40]
[47 48]]
[[49 50]
[57 58]]
[[51 52]
[59 60]]
[[53 54]
[61 62]]
[[55 56]
[63 64]]

# mean
for submatrix in submatrices:
sum = 0
for i in range (0,2):
for j in range (0,2):
sum = sum + submatrix[i][j]
print(sum/4)

5.5
7.5
9.5
11.5
21.5
23.5
25.5
27.5
37.5
39.5
41.5
43.5
53.5
55.5
57.5
59.5

# median maximum minimum


print("s.no|median|maximum|minimum")
count = 0
for submatrix in submatrices:
matrix = [element for row in submatrix for element in row]
matrix.sort()
mid = (len(matrix)-1)//2
print(f' {count} | {matrix[mid]} | {matrix[3]} |
{matrix[0]}')
count = count + 1

s.no|median|maximum|minimum
0 | 2 | 10 | 1
1 | 4 | 12 | 3
2 | 6 | 14 | 5
3 | 8 | 16 | 7
4 | 18 | 26 | 17
5 | 20 | 28 | 19
6 | 22 | 30 | 21
7 | 24 | 32 | 23
8 | 34 | 42 | 33
9 | 36 | 44 | 35
10 | 38 | 46 | 37
11 | 40 | 48 | 39
12 | 50 | 58 | 49
13 | 52 | 60 | 51
14 | 54 | 62 | 53
15 | 56 | 64 | 55

#transpose
for submatrix in submatrices:
print(submatrix.T)

[[ 1 9]
[ 2 10]]
[[ 3 11]
[ 4 12]]
[[ 5 13]
[ 6 14]]
[[ 7 15]
[ 8 16]]
[[17 25]
[18 26]]
[[19 27]
[20 28]]
[[21 29]
[22 30]]
[[23 31]
[24 32]]
[[33 41]
[34 42]]
[[35 43]
[36 44]]
[[37 45]
[38 46]]
[[39 47]
[40 48]]
[[49 57]
[50 58]]
[[51 59]
[52 60]]
[[53 61]
[54 62]]
[[55 63]
[56 64]]

#flattening row wise


for submatrix in submatrices:
matrix = [element for row in submatrix for element in row]
print(matrix)

[1, 2, 9, 10]
[3, 4, 11, 12]
[5, 6, 13, 14]
[7, 8, 15, 16]
[17, 18, 25, 26]
[19, 20, 27, 28]
[21, 22, 29, 30]
[23, 24, 31, 32]
[33, 34, 41, 42]
[35, 36, 43, 44]
[37, 38, 45, 46]
[39, 40, 47, 48]
[49, 50, 57, 58]
[51, 52, 59, 60]
[53, 54, 61, 62]
[55, 56, 63, 64]

#flattening row wise


for submatrix in submatrices:
matrix = np.array([[submatrix[0][0]],[submatrix[0][1]],
[submatrix[1][0]],[submatrix[1][1]]])
print(matrix)
print(" ")

[[ 1]
[ 2]
[ 9]
[10]]

[[ 3]
[ 4]
[11]
[12]]
[[ 5]
[ 6]
[13]
[14]]

[[ 7]
[ 8]
[15]
[16]]

[[17]
[18]
[25]
[26]]

[[19]
[20]
[27]
[28]]

[[21]
[22]
[29]
[30]]

[[23]
[24]
[31]
[32]]

[[33]
[34]
[41]
[42]]

[[35]
[36]
[43]
[44]]

[[37]
[38]
[45]
[46]]

[[39]
[40]
[47]
[48]]
[[49]
[50]
[57]
[58]]

[[51]
[52]
[59]
[60]]

[[53]
[54]
[61]
[62]]

[[55]
[56]
[63]
[64]]
10/12/23, 11:01 AM exp6

EXPERIMENT No 6 Basic Intensity


Transformation
Aim: 1.Find the negative of an image. 2.To apply power low transformation for gamma<1,
gamma=1, gamma>1 3.To apply log transformation on an image 4.To highlight certain
specified regions present in an image

In [19]: import cv2


from cv2 import imshow
import matplotlib.pyplot as plt
img1=cv2.imread('C:/Users/WT/Desktop/parvathy/parrot.jpg',cv2.IMREAD_GRAYSCALE)
img1=cv2.resize(img1,(275,180))
img2=cv2.imread('C:/Users/WT/Desktop/Parvathy/mribrain.jpg',cv2.IMREAD_GRAYSCALE)
img2=cv2.resize(img2,(275,180))
def show_images(imgs, labels, figsize):
fig=plt.figure(figsize=figsize)
for i in range(len(imgs)):
ax=fig.add_subplot(1,len(imgs),i+1)
ax.set_title(labels[i])
ax.imshow(imgs[i],cmap='gray',vmax=255,vmin=0)
print("\n input image\n")
show_images([img1, img2],["img1","img2"],(10,10))

input image

In [20]: import numpy as np


neg1 = 255 - img1
neg2 = 255 - img2
show_images([img1, neg1],["input img","negative img"],(10,10))
show_images([img2, neg2],["input img","negative img"],(10,10))

localhost:8889/nbconvert/html/exp6.ipynb?download=false 1/5
10/12/23, 11:01 AM exp6

In [22]: p=1
gamma=0.8
p_img1_L=p*(img1**gamma)
p_img2_L=p*(img2**gamma)
gamma=1
p_img1_E=p*(img1**gamma)
p_img2_E=p*(img2**gamma)
gamma=1.18
p_img1_G=p*(img1**gamma)
p_img2_G=p*(img2**gamma)
show_images([img1,p_img1_L,p_img1_E,p_img1_G ],["input img","r < 1","r=1","r>1"],(1
show_images([img2,p_img2_L,p_img2_E,p_img2_G ],["input img","r < 1","r=1","r>1"],(1

In [23]: p=15
log11= p*np.log(1.0000001 + img1)
log21= p*np.log(1.0000001 + img2)

p=30
log12= p*np.log(1.0000001 + img1)
log22= p*np.log(1.0000001 + img2)

p=55
log13= p*np.log(1.0000001 + img1)
log23= p*np.log(1.0000001 + img2)

show_images([img1,log11,log12,log13],["input img","p=15","p=30","p=55"],(16,25))
show_images([img1,log21,log22,log23],["input img","p=15","p=30","p=55"],(16,25))

localhost:8889/nbconvert/html/exp6.ipynb?download=false 2/5
10/12/23, 11:01 AM exp6

In [25]: def fg_highlight(x):


if x >=70 and x<=160:
return x+80
else:
return x

xvals = range(0, 256 ,1)


yvals = [fg_highlight(x) for x in xvals]
plt.plot(xvals,yvals)

row,col = len(img1),len(img1[0])
res_img1 = []
res_img2 =[]

for i in range(row):
temp1 = []
temp2 = []
for j in range(col):
temp1.append(fg_highlight(1+img1[i][j]))
temp2.append(fg_highlight(1+img2[i][j]))
res_img1.append(temp1)
res_img2.append(temp2)
show_images([img1, res_img1],["input img","fg highlighted image"],(10,10))
show_images([img2, res_img2],["input img","fg highlighted image"],(10,10))

localhost:8889/nbconvert/html/exp6.ipynb?download=false 3/5
10/12/23, 11:01 AM exp6

In [35]: def section_highlight(x) :


if x >=100 and x <=160:
return 200
else:
return 60

xvals = range(0, 256 ,1)


yvals = [section_highlight(x) for x in xvals]
plt.plot(xvals,yvals)

row,col = len(img1),len(img1[0])
res_img1 = []
res_img2 =[]

for i in range(row):
temp1 = []
temp2 = []
for j in range(col):
temp1.append(section_highlight(1+img1[i][j]))
temp2.append(section_highlight(1+img2[i][j]))
res_img1.append(temp1)
res_img2.append(temp2)
show_images([img1, res_img1],["input img","section highlighted image"],(10,10))
show_images([img2, res_img2],["input img","section highlighted image"],(10,10))

localhost:8889/nbconvert/html/exp6.ipynb?download=false 4/5
10/12/23, 11:01 AM exp6

Result
1.Found the negative of an image. 2.Applied power low transformation for gamma<1,
gamma=1, gamma>1 3.Applied log transformation on an image 4.Highlight certain
specified regions present in an image

localhost:8889/nbconvert/html/exp6.ipynb?download=false 5/5
10/19/23, 10:28 AM experiment 7

Experiment No 7: Mean Filtering and


Median Filtering in 2D
Aim:

1. To perform Mean filtering with filter sizes 3x3, 5x5,7x7 and 11x11
2. To perform Median filtering with filter sizes 3x3, 5x5,7x7 and 11x11
3. Add Gaussian Noise to the image and perform Mean and Median filtering
4. Add Salt & Pepper Noise to the image and perform Mean and Median filtering
Date-19/10/23

In [3]: #mean filtering


import cv2
import matplotlib.pyplot as plt
img1 = cv2.imread('C:/Users/WT LAB/Desktop/BR/parr.jpeg',cv2.IMREAD_GRAYSCALE)
img1 = cv2.resize(img1, (275, 180))
img2 = cv2.imread('C:/Users/WT LAB/Desktop/BR/parr.jpeg',cv2.IMREAD_GRAYSCALE)
img2 = cv2.resize(img2, (275, 180))
# function to display images with subplot
def show_images(imgs, labels, figsize):
fig = plt.figure(figsize=figsize)
for i in range(len(imgs)):
ax = fig.add_subplot(1, len(imgs), i+1)
ax.title.set_text(labels[i])
ax.imshow(imgs[i], cmap='gray', vmax=255, vmin=0)
print("\n Input image \n")
show_images([img1], ["img1"], (5, 5))

Input image

In [16]: filter_sizes = [(3, 3), (5, 5), (7, 7), (11, 11)]
for s in filter_sizes:
im = cv2.blur(img1, s)
show_images([img1, im], ["input", f"{s[0]}x{s[1]} mean filtered"], (8, 8))

localhost:8888/nbconvert/html/experiment 7.ipynb?download=false 1/7


10/19/23, 10:28 AM experiment 7

In [13]: #Median filtering


vals = [3, 5, 7, 11]
for s in vals:
im = cv2.medianBlur(img1, s)
show_images([img1, im], ["input", f"{s}x{s} median filtered"], (8, 8))

localhost:8888/nbconvert/html/experiment 7.ipynb?download=false 2/7


10/19/23, 10:28 AM experiment 7

In [6]: #Add Gaussian Noise to the image and perform Mean and Median filtering:
import numpy as np
row,col= img1.shape
mean = 0
var = 0.1
sigma = var**0.5
gauss = np.random.normal(mean,sigma,(row,col))
gauss = gauss.reshape(row,col)

localhost:8888/nbconvert/html/experiment 7.ipynb?download=false 3/7


10/19/23, 10:28 AM experiment 7
noisy = img1 + gauss*255
show_images([img1, gauss*255, noisy],
["input","noise","gaussian noise applied"], (12,12))

In [12]: vals = [3, 11]


for s in vals:
im = cv2.blur(noisy, [s,s])
show_images([img1, im], ["input", f"{s}x{s}mean filtered"], (8, 8))

In [11]: vals = [3, 5]


for s in vals:
im = cv2.medianBlur(noisy.astype(np.uint16), s)
show_images([img1, im], ["input", f"{s}x{s} median filtered"], (8, 8))

localhost:8888/nbconvert/html/experiment 7.ipynb?download=false 4/7


10/19/23, 10:28 AM experiment 7

In [9]: #Apply Salt & Pepper noise to image:


import random
def add_noise(img):
# Getting the dimensions of the image
row , col = img.shape
# Randomly pick some pixels in the
# image for coloring them white
# Pick a random number between 500 and 1000
number_of_pixels = random.randint(500, 1000)
for i in range(number_of_pixels):
# Pick a random y coordinate
y_coord=random.randint(0, row - 1)
# Pick a random x coordinate
x_coord=random.randint(0, col - 1)
# Color that pixel to white
img[y_coord][x_coord] = 255
# Randomly pick some pixels in
# the image for coloring them black
# Pick a random number between 500 and 1000
number_of_pixels = random.randint(500 , 1000)
for i in range(number_of_pixels):
# Pick a random y coordinate
y_coord=random.randint(0, row - 1)
# Pick a random x coordinate
x_coord=random.randint(0, col - 1)
# Color that pixel to black
img[y_coord][x_coord] = 0
return img
sp_img = add_noise(img1)
show_images([img1, sp_img], ["sd", "df"],(10,10))

localhost:8888/nbconvert/html/experiment 7.ipynb?download=false 5/7


10/19/23, 10:28 AM experiment 7

In [10]: #Apply Mean and Median filter to S&P noisy image:


vals = [3, 11]
for s in vals:
im = cv2.blur(sp_img, [s,s])
show_images([img1, im], ["input", f"{s}x{s} mean filtered"], (8, 8))
vals = [3, 5]
for s in vals:
im = cv2.medianBlur(sp_img.astype(np.uint16), s)
show_images([img1, im], ["input", f"{s}x{s} median filtered"], (8, 8))

localhost:8888/nbconvert/html/experiment 7.ipynb?download=false 6/7


10/19/23, 10:28 AM experiment 7

In [ ]:

localhost:8888/nbconvert/html/experiment 7.ipynb?download=false 7/7


10/19/23, 11:15 AM Experiment 8

Experiment No 8: Edge Detection on


Images
Aim: To perform edge detection on images using different operators:

1. Roberts operator
2. Sobel operator
3. Prewitt operator
4. Laplacian operator Date-19/10/23

In [8]: #Edge detection using Roberts operator:


# Function to display images
import cv2
import matplotlib.pyplot as plt
# from google.colab import drive
# drive.mount(’/content/drive’)
img1 = cv2.imread('C:/Users/WT LAB/Desktop/BR/camera.webp',cv2.IMREAD_GRAYSCALE)
img1 = cv2.resize(img1, (275, 180))
# function to display images with subplot h
def show_images(imgs, labels, figsize):
fig = plt.figure(figsize=figsize)
for i in range(len(imgs)):
ax = fig.add_subplot(1, len(imgs), i+1)
ax.title.set_text(labels[i])
ax.imshow(imgs[i], cmap='gray')
print("\nInput images\n")
show_images([img1], ["img1"], (5, 5))

Input images

In [17]: # perform robert edge detection:

import numpy as np
from scipy import ndimage
eb_v=np.array([[1,0],[0,-1]])
rb_h=np.array([[0,1],[-1,0]])
img=np.array(img1,dtype='float')

localhost:8888/nbconvert/html/Experiment 8.ipynb?download=false 1/3


10/19/23, 11:15 AM Experiment 8
img/=255
vertical=ndimage.convolve(img,rb_h)
horizontal = ndimage.convolve( img, rb_h )
edged_img = np.sqrt( np.square(horizontal) +np.square(vertical))
edged_img*=255
show_images([edged_img], ["Roberts Operator output"],
(5,5))

In [19]: #Edge detection using Sobel operator:


sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5) # x
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5) # y
show_images([sobelx, sobely], ["Sobel X", "Sobel Y"],
(10, 10))

In [21]: #Edge detection using Prewitt operator:


kernelx = np.array([[1,1,1],[0,0,0],[-1,-1,-1]])
kernely = np.array([[-1,0,1],[-1,0,1],[-1,0,1]])
img_prewittx = cv2.filter2D(img1, -1, kernelx)
img_prewitty = cv2.filter2D(img1, -1, kernely)
show_images([img_prewittx, img_prewitty, img_prewittx+ img_prewitty],
["img prewittx", "img prewitty","img prewittx + img prewitty"], (15, 15

localhost:8888/nbconvert/html/Experiment 8.ipynb?download=false 2/3


10/19/23, 11:15 AM Experiment 8

In [23]: #Edge detection using Laplacian operator:


laplacian = cv2.Laplacian(img,cv2.CV_64F)
show_images([img1, laplacian], ["img1", "laplacian"],
(10, 10))

In [ ]:

localhost:8888/nbconvert/html/Experiment 8.ipynb?download=false 3/3

You might also like