0% found this document useful (0 votes)
15 views30 pages

ASIP Practical

The document outlines various practical programming exercises related to signal processing and image processing techniques, including upsampling, downsampling, convolution, template matching, and noise smoothing. It provides code snippets for each task using libraries like OpenCV, NumPy, and Matplotlib, demonstrating operations such as edge detection, morphological transformations, and feature extraction. Each practical aims to enhance understanding of image processing concepts through hands-on coding examples.

Uploaded by

vishu.waghmare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views30 pages

ASIP Practical

The document outlines various practical programming exercises related to signal processing and image processing techniques, including upsampling, downsampling, convolution, template matching, and noise smoothing. It provides code snippets for each task using libraries like OpenCV, NumPy, and Matplotlib, demonstrating operations such as edge detection, morphological transformations, and feature extraction. Each practical aims to enhance understanding of image processing concepts through hands-on coding examples.

Uploaded by

vishu.waghmare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Practical No: 1

Aim :- Write program to demonstrate the following aspects of signal processing on


suitable data
1. Upsampling and downsampling on Image/speech signal
# Import cv2, matplotlib, numpy
import cv2
import matplotlib.pyplot as plt
import numpy as np

# Read the original image and know its type


img1 = cv2.imread('g4g.png', 0)

# Obtain the size of the original image


[m, n] = img1.shape
print('Image Shape:', m, n)

# Show original image


print('Original Image:')
plt.imshow(img1, cmap="gray")

# Down sampling

# Assign a down sampling rate


# Here we are down sampling the
# image by 4
f=4

# Create a matrix of all zeros for


# downsampled values
img2 = np.zeros((m//f, n//f), dtype=np.int)

# Assign the down sampled values from the original


# image according to the down sampling frequency.
# For example, if the down sampling rate f=2, take
# pixel values from alternate rows and columns
# and assign them in the matrix created above
for i in range(0, m, f):
for j in range(0, n, f):
try:
img2[i//f][j//f] = img1[i][j]
except IndexError:
pass

# Show down sampled image


print('Down Sampled Image:')
plt.imshow(img2, cmap="gray")

# Up sampling

# Create matrix of zeros to store the upsampled image


img3 = np.zeros((m, n), dtype=np.int)
# new size
for i in range(0, m-1, f):
for j in range(0, n-1, f):
img3[i, j] = img2[i//f][j//f]

# Nearest neighbour interpolation-Replication


# Replicating rows

for i in range(1, m-(f-1), f):


for j in range(0, n-(f-1)):
img3[i:i+(f-1), j] = img3[i-1, j]

# Replicating columns
for i in range(0, m-1):
for j in range(1, n-1, f):
img3[i, j:j+(f-1)] = img3[i, j-1]

# Plot the up sampled image


print('Up Sampled Image:')
plt.imshow(img3, cmap="gray")

Input :
Output:
Original Image:

Down Sampled Image:

Up Sampled Image:
Practical No- 2

Aim :- Write program to perform the following on signal

1.Create a triangle signal and plot a 3-period segment.

from scipy import signal


import matplotlib.pyplot as plot
import numpy as np
t = np.linspace(0, 1, 1000, endpoint=True)
# Plot the sawtooth wave
plot.plot(t, signal.sawtooth(2 * np.pi * 5 * t))
# Give x, y, title axis label
plot.xlabel('Time')
plot.ylabel('Amplitude')
plot.title('Sawtooth Signal - Geeksforgeeks')
plot.axhline(y=0, color='k')
# Display
plot.show()

Output :
2.For a given signal, plot the segment and compute the correlation between them.

importnumpy as np
importmatplotlib.pyplot as plt

# signal 1
time1=np.arange(0,100,0.1)
cossignal1=np.cos(time1)
plt.plot(cossignal1)
plt.title("Signal 1")
plt.show()

# signal 2
time2=np.arange(0,100,0.1)
cossignal2=np.cos(time2)
plt.plot(cossignal2)
plt.title("Signal 2")
plt.show()

# Store the value of correlation in a


# variable say 'cor' using the following code:
cor=plt.cohere(cossignal1,cossignal2)
# plot the coherence graph
plt.show()

Output:
Practical No 3

Aim: Write program to demonstrate the following aspects of signal on image data

1. Convolution operation

import cv2
import numpy as np
image = cv2.imread('Flower.jpg')

# Apply blurring kernal


blur_kernel = np.ones((5 ,5), np.float32) / 25
blur_img = cv2.filter2D(src=image, ddepth =-1, kernel=blur_kernel)

# Apply Sharpning kernal


sharp_kernel = np.array([[0, -1, 0],[-1, 5, -1],[0, -1, 0]])
sharp_img = cv2.filter2D(src=image, ddepth =-1, kernel=sharp_kernel)

cv2.imshow('Orginal',image)
cv2.imshow('Sharpened',sharp_img)
cv2.imshow('Kernel blur',blur_img)
cv2.imwrite('sharp_image.jpg',sharp_img)
cv2.imwrite('blur_kernel.jpg',blur_img)
cv2.waitKey()
cv2.destroyAllWindows()

Input

Orginal
Output

Sharpened

Kernel blur
2. Template Matching

#Python program to illustrate


#Templatemacthing
import cv2
import numpy as np
#Read the main image
img_rgb = cv2.imread('Sprite.jpg')
#Convert it to grayscale
img_grey = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
#Read the template
template = cv2.imread('Template.jpg',0)
#Store width and height of template in w and h
w,h = template.shape[::-1]
#Perform match operations
res = cv2.matchTemplate(img_grey,template,cv2.TM_CCOEFF_NORMED)
#Specifying a threshhold
threshold = 0.8
#Store the coordinates of matched area in a numpy array

oc = np.where(res >= threshold)


#Draw a rectangle arounch the matched region
for pt in zip(*oc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h),(0,255,255),2)
#Show the final image with the matched area
cv2.imshow('Detected',img_rgb)

Input
Sprite.jpg
Template.jpg

Output

Detected Image
Practical No - 4
Aim :- Write program to implement point/pixel intensity transformations such as

1. Log and Power-law transformations :

import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read an image
image = cv2.imread('g4g.png')
# Apply log transformation method
c = 255 / np.log(1 + np.max(image))
log_image = c * (np.log(image + 1))
# Specify the data type so that
# float value will be converted to int
log_image = np.array(log_image, dtype = np.uint8)
# Display both images
plt.imshow(image)
plt.show()
plt.imshow(log_image)
plt.show()

Input Image: Output Image:


2. Contrast adjustments:

from PIL import Image,ImageEnhance


img=Image.open("844792.jpg")
img.show()
img_contr_obj=ImageEnhance.Contrast(img)
factor=20
e_img=img_contr_obj.enhance(factor)
e_img.show()
img_contr_obj=ImageEnhance.Contrast(img)
factor=-10
e_img1=img_contr_obj.enhance(factor)
e_img1.show()

Input Image:

Output Image High Pass:


Output Image Low Pass:
3. Histogram equalization:

# import Opencv
import cv2
# import Numpy
import numpy as np
import matplotlib.pyplot as plt #importing matplotlib
# read a image using imread
img = cv2.imread('download.jpg', 0)
histr = cv2.calcHist([img],[0],None,[256],[0,256])
# show the plotting graph of an image
plt.plot(histr)
plt.show()
# creating a Histograms Equalization
# of a image using cv2.equalizeHist()
equ = cv2.equalizeHist(img)
# stacking images side-by-side
res = np.hstack((img, equ))
# show image input vs output
cv2.imshow('image', res)
histr = cv2.calcHist([res],[0],None,[256],[0,256])
# show the plotting graph of an image
plt.plot(histr)
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()

Input / Output Image:


Input Image Histogram: Output Image Histogram:
4. Thresholding, and halftoning operations:

# Python program to illustrate


# simple thresholding type on an image
# organizing imports
import cv2
import numpy as np
# path to input image is specified and
# image is loaded with imread command
image1 = cv2.imread('g4g.png')
# cv2.cvtColor is applied over the
# image input with applied parameters
# to convert the image in grayscale
img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
# applying different thresholding
# techniques on the input image
# all pixels value above 120 will
# be set to 255
ret, thresh1 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img, 120, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img, 120, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img, 120, 255, cv2.THRESH_TOZERO_INV)
# the window showing output images
# with the corresponding thresholding
# techniques applied to the input images
cv2.imshow('Binary Threshold', thresh1)
cv2.imshow('Binary Threshold Inverted', thresh2)
cv2.imshow('Truncated Threshold', thresh3)
cv2.imshow('Set to 0', thresh4)
cv2.imshow('Set to 0 Inverted', thresh5)
# De-allocate any associated memory usage
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()

Input Image:
Output Image of 'Binary Threshold': Output Image of 'Set to 0', thresh4’:

Output Image of 'Binary Threshold Output Image of 'Set to 0 Inverted':


Inverted':

Output Image of 'Truncated Threshold':


Practical No: 5
Aim : Write a program to apply various enhancements on images using image
derivatives by implementing Gradient and Laplacian operations

Code :

import cv2

img = cv2.imread("E:\PYTHON\earth.jpg")

ddepth = cv2.CV_16S

kernel_size =3

red_Noise = cv2.GaussianBlur(img,(3,3),0)

gray=cv2.cvtColor(red_Noise,cv2.COLOR_BGR2GRAY)

dst=cv2.Laplacian(gray,ddepth,ksize=kernel_size)

abs_dst=cv2.convertScaleAbs(dst)

cv2.imshow('original image',img)

cv2.imshow('Laplacian image',abs_dst)

Input Image: Output Image:


Practical No : 6
Aim : Write a program to implement linear and nonlinear noise smoothing on suitable image or
sound signal.

Code:

import numpy as np

import cv2

from matplotlib import pyplot as plt

from PIL import Image,ImageFilter

image = cv2.imread("E:/PYTHON/nature.jpg") #reads the image

image = cv2.cvtColor(image,cv2.COLOR_BGR2HSV) #convert to HSV

figure_size=9 #the dimension of the x and y axis of the kernel

#Generate Gaussian noise

gauss = np.random.normal(0,1,image.size)

gauss = gauss.reshape(image.shape[0],image.shape[1],image.shape[2]).astype('uint8')

#Add the Gaussian noise to the image

img_gauss = cv2.add(image,gauss)

#noiseImg = red_Noise=cv2.GaussianBlur(image,(3,3),0)

new_image=cv2.GaussianBlur(image,(figure_size,figure_size),0)

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

plt.subplot(121)

plt.imshow(cv2.cvtColor(img_gauss,cv2.COLOR_HSV2RGB))

plt.title('Gaussian Noise')

plt.xticks([]),plt.yticks([])

plt.subplot(122),plt.imshow(cv2.cvtColor(new_image,cv2.COLOR_HSV2RGB)),plt.title('Gaussian Filter')

plt.xticks([]),plt.yticks([])

plt.show()
Output:
Practical No: 7
Aim: Write a program to apply various image enhancement using image
derivatives by implementing smoothing filters for generating suitable images for
specific application requirements.
Code :
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('eye.jpg')
kernel = np.ones((5,5),np.float32)/25
dst=cv2.filter2D(img,-1,kernel)
plt.subplot(121),plt.imshow(img),plt.title('original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(dst),plt.title('Smoothened Image')
plt.xticks([]),plt.yticks([])
plt.show()

OUTPUT
Practical No: 8
Aim - Write a program to Apply edge detection techniques such as Sobel and
Canny to extract meaningful information from the given image samples

Code –
import cv2

img=cv2.imread('D:/flower_image.jpg')

cv2.imshow('Original',img)

cv2.waitKey(0)

img_gry=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

img_blur=cv2.GaussianBlur(img_gry,(3,3),0)

sobelx=cv2.Sobel(src=img_blur,ddepth=cv2.CV_64F,dx=1,dy=0,ksize=5)

sobely=cv2.Sobel(src=img_blur,ddepth=cv2.CV_64F,dx=0,dy=1,ksize=5)

sobelxy=cv2.Sobel(src=img_blur,ddepth=cv2.CV_64F,dx=1,dy=1,ksize=5)

cv2.imshow('SobelX',sobelx)

cv2.waitKey(0)

cv2.imshow('SobelY',sobely)

cv2.waitKey(0)

cv2.imshow('SobelXY',sobelxy)

cv2.waitKey(0)

edges=cv2.Canny(image=img_blur,threshold1=100,threshold2=200)

cv2.imshow('Canny Edge Detection',edges)

cv2.waitKey(0)

cv2.destroyAllWindows()
Output : Original image

Sobely sobelx

sobelxy Canny Edge Detection


Practical No : 9
Aim - Write the program to implement various morphological image processing
techniques.

Erosion and Dilation

Code -
import cv2

import numpy as np

image=cv2.imread('x.jpg')

kernel=np.ones((5,5),np.uint8)

erosion=cv2.erode(image,kernel,iterations=1)

dilation=cv2.dilate(image,kernel,iterations=1)

cv2.imshow('input',image)

cv2.imshow('erosion',erosion)

cv2.imshow('dilation',dilation)
output –

original image -

Erosion -

Dilation –
Opening and Closing

Code-
import cv2

import numpy as np

image=cv2.imread('opening.png')

kernel=np.ones((5,5),np.uint8)

opening=cv2.morphologyEx(image,cv2.MORPH_OPEN,kernel)

closing=cv2.morphologyEx(image,cv2.MORPH_CLOSE,kernel)

gradient=cv2.morphologyEx(image,cv2.MORPH_GRADIENT,kernel)

cv2.imshow('input',image)

cv2.imshow('opening',opening)

cv2.imshow('closeing',closing)

output -

original image –
Opening –

Closing –
Practical no: 10

Aim:- Write the program to extract image features by implementing methods


like corner and blob detectors, HoG and Haar features.

1) Blob Detector

import cv2

import numpy as np

img = cv2.imread('C:/messi/ronaldo.jpg')

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

gray = np.float32(gray)

dst = cv2.cornerHarris(gray,2,3,0.04)

dst = cv2.dilate(dst,None)

img[dst>0.01*dst.max()]=[0,0,255]

cv2.imshow('output',img)

cv2.imwrite('corner10.1_output.jpg',img)

Output:
2) Hog

import cv2

from skimage.feature import hog

ori = cv2.imread('D:/signallingpractical/house-sparrow-1.webp')

img = cv2.imread('D:/signallingpractical/house-sparrow-1.webp')

_,hog_image =
hog(img,orientations=8,pixels_per_cell=(7,7),cells_per_block=(1,1),visualize=True,multichanne
l = True)

cv2.imshow('Original Image',ori)

cv2.imshow('Hog',hog_image)

cv2.imwrite('Original Image',ori)

cv2.imwrite('Hog',hog_image)

Output:

3) Harr

import cv2

import numpy as np

import matplotlib.pyplot as plt

face_cascade=cv2.CascadeClassifier('C:/Python310/Lib/site-
packages/cv2/data/haarcascade_frontalface_default.xml')
eye_cascade=cv2.CascadeClassifier('C:/Python310/Lib/site-
packages/cv2/data/haarcascade_eye.xml')

img = cv2.imread('C:/messi/ronaldo.jpg')

gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

faces=face_cascade.detectMultiScale(gray,1.3,5)

for(x,y,w,h)in faces:

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

roi_gray=gray[y:y+h,x:x+w]

roi_color=img[y:y+h,x:x+w]

eyes=eye_cascade.detectMultiScale(roi_gray)

for(ex,ey,ew,eh) in eyes:

cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)

cv2.imwrite('detected.jpg',img)

cv2.waitKey(0)

cv2.destroyAllWindows()

Output:
Practical No: 11

Aim: Write the program to apply segmentation for detecting lines, circles, and
other shapes/objects. Also, implement edge-based and region-based
segmentation.

Code:

import numpy as np
import cv2 as cv
img = cv.imread('opencv-logo-white.png',0)
img = cv.medianBlur(img,5)
cimg = cv.cvtColor(img,cv.COLOR_GRAY2BGR)
circles = cv.HoughCircles(img,cv.HOUGH_GRADIENT,1,20,
param1=50,param2=30,minRadius=0,maxRadius=0)
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
# draw the outer circle
cv.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
cv.imshow('detected circles',cimg)
cv.waitKey(0)
cv.destroyAllWindows()

Output:

You might also like