Professional Documents
Culture Documents
RECORD NOTEBOOK
Name : J DHARSHAN
Register No : 191081101606
Degree : B.Tech
BONAFIDE
CERTIFICATE
Register No : 191081101606
Name Of The Lab : OpenCV – Python for Digital Image Processing Lab
Department : ELECTRONICS AND COMMUNICATION ENGINEERING
Certified that this is a bonafide of record work done by
J DHARSHAN of the IV / VII / A class in the
OPENCV – PYTHON FOR DIGITAL IMAGE PROCESSING laboratory
intheacademicyear 20 22 -20 23
LIST OF
EXPERIMENTS
S.NO. DATE CONTENT PAGE FACULITY
NO. SIGNATURE
4 15-21
Geometric Transformation of an
Image
6 29-37
Morphological transformation of an
Image
7 38-42
Image Gradient
8 43-45
Canny Edge Detection
9 46-52
Image Pyramids
10 53-56
Contours
11 57-63
Histograms of an Image
12 64-68
Fourier Transforms of an Image
13 69-71
Feature Detection and Description
14 72-75
Camera Calibration and 3D Reconstruction
3
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
IMAGE PROCESSING IN OPENCV
EXP NO.: 01
What is OpenCV?
This might be the 'basic' question that comes first to our mind. Well, it stands for ‘Open Source
Computer Vision Library’ initiated by some enthusiast coders in ‘1999’ to incorporate Image
Processing into a wide variety of coding languages. It has C++, C, and Python interfaces running
on Windows, Linux, Android and Mac.
Before, we get into the use of OpenCV; Let’s get familiar with the same. As, we must have
understood that it is a 'library', so to use the functions available in the library we would need a
compiler.
To start off, we need to install 'OpenCV' and a 'compiler' and then establish a linkage between
the two(i.e. Compiler is able to use the functions available with the library).
Basically there are four modules.
IMAGE PROCESSING
4
BEC18L11 Open CV-Python For Digital Image Processing
1. Binary Image.
2. Grayscale Image.
3. Coloured Image. (RGB)
Each kind of image has a few attributes attached to it like number of channels and depth .
1. BINARY IMAGE
Again, as the name suggests each number associated with the pixel can have just one of the
two possible values.
2. GRAYSCALE IMAGE
5
BEC18L11 Open CV-Python For Digital Image Processing
1. R : 0-255
2. G : 0- 255
3. B : 0-255
Each number between 0-255 corresponds to a shade of corresponding color
Depth of a RGB image is 8(bits)
Number of channels for an RGB image is 3.
CREATING AN IMAGE
This will create a RGB image (most general case among the three types of images
discussed) without specifying pixel values.
6
BEC18L11 Open CV-Python For Digital Image Processing
Erosion
Dilation
For carrying out morphological operations we need to specify type of structural element
and number of iterations.
Erosion erodes the image. It tries to bring uniformity in the image by converting
bright points inneighborhoods of points of less intensity into darker ones.
Dilation dilates the image. It tries to bring uniformity in image by converting
dark points inneighborhoods of points of higher intensity into bright ones.
2. Thresholding an image:
Thresholding an image is one of the simplest ways of image segmentation.As the name suggests,
it carries out its change according to a set threshold.To threshold an image following function is
used:
cvThreshold(input, output, threshold, maxValue, thresholdType)
3. Video Input:
4. Camera Input:
First camera needs to be initialized and then image is captured and further operations can be
carried outon that image.
7
BEC18L11 Open CV-Python For Digital Image Processing
0 stands for default webcam and to access other cameras connected to the computer use 1 as
argument. Starting a camera takes time, so make sure that sufficient time has passed before we
capture the image.
This is similar to video input. All we need is attach the video from the camera to the input
stream.Following function helps us do so:
CvCapture *capture=cvCreateCameraCapture(0);
There is no need to initialize the camera in this case because frames are captured regularly.
Again, 0 for default webcam and 1 for input through external camera.
8
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
CHANGING COLOR SPACE
EXP NO.: 02
AIM:
To write a program in python using openCV for changing the color space and to get the
output using OpenCV.
THEORY:
There are more than 150 color-space conversion methods available in OpenCV. But wewill
look into only two which are most widely used ones, BGRGray and BGR HSV.
For color conversion, we use the function
cv2.cvtColor(input_image, flag)
where flag determinesthe type of conversion.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
Step 4: Run the program.
Step 5: The output will be obtained in the respective window.
9
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
import cv2
import numpy as np
cap=cv2.VideoCapture(0)
while(1):
#Take each frame
_, frame=cap.read()
if k==27:
break
cv2.destroyAllWindows()
10
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
RESULT:
Thus, the program for changing the color space is executed using openCV – python and
the output is verified successfully.
11
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
IMAGE THRESHOLDING
EXP NO.: 03
AIM:
To write a program in python using openCV functions for thresholding of an image and to
get the output using openCV.
THEORY:
Thresholding is a technique in OpenCV, which is the assignment of pixel values in relation to
the threshold value provided. In thresholding, each pixel value is compared with the threshold
value. If the pixel value is smaller than the threshold, it is set to 0, otherwise, it is set to a
maximum value (generally 255). Thresholding is a very popular segmentation technique, used
for separating an object considered as a foreground from its background. A threshold is a value
which has two regions on its either side i.e. below the threshold or above the threshold.
In Computer Vision, this technique of thresholding is done on grayscale images. So initially, the
image has to be converted in grayscale color space.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
Step 4: Run the program.
Step 5: The output will be obtained in the respective window.
12
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
import cv2
import numpy as np
img = cv2.imread('img_archer.jpg')
cv2.imshow('original',img)
cv2.imshow('threshold',threshold)
cv2.imshow('threshold2',threshold2)
cv2.imshow('gaus', gaus)
cv2.imshow('otsud',otsu)
cv2.waitKey(0)
cv2.destroyAllWindows()
13
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
RESULT:
Thus, the program for thresholding of an image is executed using openCV – python and
the output is verified successfully.
14
BEC18L11 Open CV-Python For Digital Image Processing
AIM:
To write a program in python using openCV functions for geometric transformations of an
image and to get the output using openCV.
THEORY:
Geometric transformation is an essential image processing techniques that have wide
applications. For example, a simple use case would be in computer graphics to simply rescale the
graphics content when displaying it on a desktop vs. mobile.
It could also be applied to projectively warp an image to another image plane. For
instance,instead of looking at a scene straight ahead, we wish to look at it from another
viewpoint, perspective transformation is applied in this scenario to achieve that.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
Step 4: Run the program.
Step 5: The output will be obtained in the respective window.
15
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
Scaling:
import cv2
import numpy as np
img = cv2.imread('img_archer.jpg')
cv2.imshow('Orginal',img)
cv2.imshow('Scale',res)
cv2.waitKey(0)
cv2.destroyAllWindows()
Translation:
import cv2
import numpy as np
img = cv2.imread('img_archer.jpg',0)
rows,cols = img.shape
M = np.float32([[1,0,100],[0,1,50]])
dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imshow('original',img)
cv2.imshow('img',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
16
BEC18L11 Open CV-Python For Digital Image Processing
Rotation:
import cv2
import numpy as np
img = cv2.imread('img_archer.jpg',0)
rows,cols = img.shape
M = cv2.getRotationMatrix2D((cols/2,rows/2),180,1)
dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imshow('Orginal',img)
#cv2.imshow('Rotation',M)
cv2.imshow('warpAffine',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
Affine Transformation:
import cv2
import numpy as np
from matplotlib import pyplot as
plt img =
cv2.imread('img_archer.jpg')
rows,cols,ch = img.shape
pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])
M = cv2.getAffineTransform(pts1,pts2)
dst = cv2.warpAffine(img,M,(cols,rows))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.xticks([]),plt.yticks([])
17
BEC18L11 Open CV-Python For Digital Image Processing
plt.show()
Perspective transformation:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_archer.jpg')
rows,cols,ch=img.shape pts1=np.float32([[56,65],
[368,52],[28,387],[389,390]])
pts2=np.float32([[0,0],[300,0],[0,300],[300,300]])
M=cv2.getPerspectiveTransform(pts1,pts2)
dst=cv2.warpPerspective(img,M,(300,300))
plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.xticks([]),plt.yticks([])
plt.show()
18
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
Scaling:
Translation:
19
BEC18L11 Open CV-Python For Digital Image Processing
Rotation:
Affine Transformation:
20
BEC18L11 Open CV-Python For Digital Image Processing
Perspective Transformation:
RESULT:
Thus, the program for geometric transformations of an image is executed using openCV –
python and the output is verified successfully.
21
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
SMOOTHING IMAGES
EXP NO.: 05
AIM:
To write a program in python using openCV functions for smoothing of an image with
filters and to get the output using openCV.
THEORY:
Image blurring is achieved by convolving the image with a low-pass filter kernel. It is useful for
removing noise. It actually removes high frequency content (e.g: noise, edges) from the image
resulting in edges being blurred when this is filter is applied. (Well, there are blurring
techniques which do not blur edges). OpenCV provides mainly four types of blurring techniques.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
22
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
Image Filtering Program:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_naruto.jpg')
kernel=np.ones((5,5),np.float32)/25
filtering=cv2.filter2D(img,-1,kernel)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(filtering),plt.title('filtering')
plt.xticks([]),plt.yticks([])
plt.show()
Averaging:
import cv2
import numpy as np
from matplotlib import pyplot as
plt
img=cv2.imread('img_naruto.jpg')
blur=cv2.blur(img,(9,5))
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(blur),plt.title('Blurred')
plt.xticks([]),plt.yticks([])
plt.show()
23
BEC18L11 Open CV-Python For Digital Image Processing
Guassian Filtering:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_naruto.jpg')
gaussian=cv2.GaussianBlur(img,(1,5),0)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(gaussian),plt.title('gaussian')
plt.xticks([]),plt.yticks([])
plt.show()
Median Filtering:
import cv2
import numpy as np
from matplotlib import pyplot as
plt
img=cv2.imread('img_naruto.jpg')
median=cv2.medianBlur(img,5)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(median),plt.title('Median')
plt.xticks([]),plt.yticks([])
24
BEC18L11 Open CV-Python For Digital Image Processing
plt.show()
Bilateral Filtering
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_naruto.jpg')
blur=cv2.bilateralFilter(img,9,75,75)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(blur),plt.title('Bilateral')
plt.xticks([]),plt.yticks([])
plt.show()
25
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
Image Filtering:
Averaging:
26
BEC18L11 Open CV-Python For Digital Image Processing
Gaussian Filtering:
Median Filtering:
27
BEC18L11 Open CV-Python For Digital Image Processing
Bilateral Filtering:
RESULT:
Thus, the program for smoothing of an image is executed using openCV – python and the
output is verified successfully.
28
BEC18L11 Open CV-Python For Digital Image Processing
AIM:
To write a program in python using openCV functions for morphological transformations
of an image and to get the output using openCV.
THEORY:
Morphological transformations are some simple operations based on the image shape. It is
normally performed on binary images. It needs two inputs, one is our original image, second one
is called structuring element or kernel which decides the nature of operation. Two basic
morphological operators are Erosion and Dilation. Then its variant forms like Opening,
Closing, Gradient etc also comes into play.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
29
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
Erosion:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_boruto.jpg',0)
kernel=np.ones((7,7),np.uint8)
erosion=cv2.erode(img,kernel,iterations=1)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(erosion),plt.title('Erosion')
plt.xticks([]),plt.yticks([])
plt.show()
Dilation:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_boruto.jpg',0)
kernel=np.ones((7,7),np.uint8)
dilation=cv2.dilate(img,kernel,iterations=1)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(dilation),plt.title('Dilation')
plt.xticks([]),plt.yticks([])
plt.show()
30
BEC18L11 Open CV-Python For Digital Image Processing
Opening:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_boruto.jpg',0)
kernel=np.ones((7,7),np.uint8)
opening=cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(opening),plt.title('opening')
plt.xticks([]),plt.yticks([])
plt.show()
Closing:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_boruto.jpg',0)
kernel=np.ones((7,7),np.uint8)
closing=cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(closing),plt.title('closing')
plt.xticks([]),plt.yticks([])
31
BEC18L11 Open CV-Python For Digital Image Processing
plt.show()
Morphological Gradient:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_boruto.jpg',0)
kernel=np.ones((7,7),np.uint8)
gradient=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(gradient),plt.title('gradient')
plt.xticks([]),plt.yticks([])
plt.show()
Top Hat:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_boruto.jpg',0)
kernel=np.ones((7,7),np.uint8)
tophat=cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
32
BEC18L11 Open CV-Python For Digital Image Processing
plt.subplot(122),plt.imshow(tophat),plt.title('tophat')
plt.xticks([]),plt.yticks([])
plt.show()
Black Hat:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_boruto.jpg',0)
kernel=np.ones((7,7),np.uint8)
blackhat=cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(blackhat),plt.title('blackhat')
plt.xticks([]),plt.yticks([])
plt.show()
33
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
Erosion:
Dilation:
34
BEC18L11 Open CV-Python For Digital Image Processing
Opening:
Closing:
35
BEC18L11 Open CV-Python For Digital Image Processing
Morphological Gradient:
Top Hat:
36
BEC18L11 Open CV-Python For Digital Image Processing
Black Hat:
RESULT:
Thus, the program for morphological transformations of an image is executed using
openCV – python and the output is verified successfully.
37
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
IMAGE GRADIENT
EXP NO.: 07
AIM:
To write a program in python using openCV functions for image gradient of an image using
filters and to get the output using openCV.
THEORY:
OpenCV provides three types of gradient filters or High-pass filters, Sobel, Scharr and
Laplacian. We will see each one of them.
2. Laplacian Derivatives
It calculates the Laplacian of the image given by the relation,
where each derivative is found using Sobel derivatives. If ksize = 1, then following kernel is
used for filtering:
38
BEC18L11 Open CV-Python For Digital Image Processing
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
PROGRAM:
Program 1:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_bleach.png',0)
laplacian=cv2.Laplacian(img,cv2.CV_64F)
sobelx=cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
sobely=cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)
plt.subplot(2,2,1),plt.imshow(img,cmap='gray')
plt.title('Original'),plt.xticks([]),plt.yticks([])
plt.subplot(2,2,2),plt.imshow(laplacian,cmap='gray')
39
BEC18L11 Open CV-Python For Digital Image Processing
plt.title('Laplacian'),plt.xticks([]),plt.yticks([])
plt.subplot(2,2,3),plt.imshow(sobelx,cmap='gray')
plt.title('Sobel X'),plt.xticks([]),plt.yticks([])
plt.subplot(2,2,4),plt.imshow(sobely,cmap='gray')
plt.title('Sobel Y'),plt.xticks([]),plt.yticks([])
plt.show()
Program 2:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_bleach.png',0)
sobelx64f=cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
abs_sobel64f=np.absolute(sobelx64f)
sobel_8u=np.uint8(abs_sobel64f)
plt.subplot(1,3,1),plt.imshow(img,cmap='gray')
plt.title('Original'),plt.xticks([]),plt.yticks([])
plt.subplot(1,3,2),plt.imshow(sobel_8u,cmap='gray')
plt.title('SobelCV_8U'),plt.xticks([]),plt.yticks([])
plt.subplot(1,3,3),plt.imshow(sobelx64f,cmap='gray')
plt.title('Sobelabs(CV_64F)'),plt.xticks([]),plt.yticks([])
plt.show()
40
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
Program 1:
Program 2:
41
BEC18L11 Open CV-Python For Digital Image Processing
RESULT:
Thus, the program for image gradient of an image using filters is executed using openCV
– python and the output is verified successfully.
42
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
CANNY EDGE DETECTION
EXP NO.: 08
AIM:
To write a program in python using openCV functions for canny edge detection of an image
and to get the output using openCV.
THEORY:
OpenCV puts all the above in single function, cv2.Canny(). We will see how to use it. First
argument is our input image. Second and third arguments are our minVal and maxVal
respectively. Third argument is aperture_size. It is the size of Sobel kernel used for find image
gradients. By default it is 3. Last argument is L2 gradient which specifies the equation for
finding gradient magnitude. If it is True, it uses the equation mentioned above which is more
accurate,
otherwise it uses this function:
By default, it is false.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
PROGRAM:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img_death_note.jpg',0)
edges=cv2.Canny(img,100,200)
plt.subplot(121),plt.imshow(img)
plt.title('OriginalImage'),plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap='gray')
plt.title('EdgeImage'),plt.xticks([]),plt.yticks([])
plt.show()
OUTPUT:
44
BEC18L11 Open CV-Python For Digital Image Processing
RESULT:
Thus, the program for canny edge detection of an image is executed using openCV –
python and the output is verified successfully.
45
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
IMAGE PYRAMIDS
EXP NO.: 09
AIM:
To write a program in python using openCV functions for image pyramids of an image
using filters and to get the output using openCV.
THEORY:
1. Image Pyramids : Image Pyramids are one of the most beautiful concept of image
processing.Normally, we work with images with default resolution but many times
we need to change the resolution (lower it) or resize the original image in that case
image pyramids comes handy. The pyrUp() function increases the size to double of
its original size and pyrDown() functiondecreases the size to half. If we keep the
original image as a base image and go on applying pyrDown function on it and
keep the images in a vertical stack, it will look like a pyramid. The same is true for
upscaling the original image by pyrUp function.
2. Image Blending using Image Pyramids : One application of Pyramids is Image
Blending. For example, in image stitching, you will need to stack two images
together,
but it may not loo good due to discontinuities between images. In that case, image
k
blending with Pyramids gives you seamless blending without leaving much data in
the images. One classical example of this isthe blending of two fruits, Orange and
Apple.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV
and matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
46
BEC18L11 Open CV-Python For Digital Image Processing
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
PROGRAM:
Image Pyramids:
import cv2
import numpy as np
img = cv2.imread("img_rengoku.png")
# Gaussian Pyramid
layer = img.copy()
gaussian_pyramid = [layer]
for i in range(6):
layer = cv2.pyrDown(layer)
gaussian_pyramid.append(layer)
# Laplacian Pyramid
layer = gaussian_pyramid[5]
cv2.imshow("6", layer)
laplacian_pyramid = [layer]
47
BEC18L11 Open CV-Python For Digital Image Processing
laplacian_pyramid.append(laplacian)
cv2.imshow(str(i), laplacian)
Image Blending:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img1 = cv2.imread("img_nezuko.jpg")
img1 = cv2.resize(img1, (1000, 1000))
img2 = cv2.imread("img_tanjiro.jpg")
img2 = cv2.resize(img2, (1000, 1000))
for i in range(6):
layer = cv2.pyrDown(layer)
gaussian_pyramid.append(layer)
# Laplacian Pyramid 1
layer = gaussian_pyramid[5]
laplacian_pyramid = [layer]
48
BEC18L11 Open CV-Python For Digital Image Processing
# Gaussian Pyramid 2
layer = img2.copy()
gaussian_pyramid2 = [layer]
for i in range(6):
layer = cv2.pyrDown(layer)
gaussian_pyramid2.append(layer)
# Laplacian Pyramid 2
layer = gaussian_pyramid2[5]
laplacian_pyramid2 = [layer]
49
BEC18L11 Open CV-Python For Digital Image Processing
# Reconstructed Footbase_ball
footbase_ball_reconstructed = footbase_ball_pyramid[0]
plt.subplot(1,2,1),plt.imshow(footbase_ball_reconstructed)
plt.title('Footbase Ball Reconstructed'), plt.xticks([]), plt.yticks([])
plt.subplot(1,2,2),plt.imshow(footbase_ball)
plt.title('Footbase Ball'), plt.xticks([]), plt.yticks([])
plt.show()
50
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
Image Pyramids:
Image Blending:
51
BEC18L11 Open CV-Python For Digital Image Processing
RESULT:
Thus, the program for image pyramids of an image is executed using openCV – python
and the output is verified successfully.
52
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
CONTOURS
EXP NO.: 10
AIM:
To write a program in python using openCV functions for contours of an image using filters
and to get the output using openCV.
THEORY:
Contours are defined as the line joining all the points along the boundary of an image that are
having the same intensity. Contours come handy in shape analysis, finding the size of the
object of interest, and object detection.
OpenCV has findContour() function that helps in extracting the contours from the image. It
works best on binary images, so we should first apply thresholding techniques, Sobel edges, etc.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
53
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
import cv2
import matplotlib.pyplot as plt
# convert to RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# show it
plt.imshow(binary, cmap="gray")
plt.show()
plt.show()
54
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
55
BEC18L11 Open CV-Python For Digital Image Processing
RESULT:
Thus, the program for contours of an image is executed using openCV – python and the
output is verified successfully.
56
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
HISTOGRAMS OF AN IMAGE
EXP NO.: 11
AIM:
To write a program in python using openCV functions for histograms of an image using
filters and to get the output using openCV.
THEORY:
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
57
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
Histogram:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("img_one_piece.jpg")
b, g, r = cv2.split(img)
plt.subplot(2,2,1),plt.imshow(img)
plt.title('Original image'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,2),plt.imshow(b)
plt.title('B'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,3),plt.imshow(g)
plt.title('G'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,4),plt.imshow(r)
plt.title('R'), plt.xticks([]), plt.yticks([])
plt.show()
plt.show()
58
BEC18L11 Open CV-Python For Digital Image Processing
Histogram Equilizer:
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('img_one_piece.jpg',0)
hist,bins = np.histogram(img.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * float(hist.max()) / cdf.max()
plt.show()
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img=cv.imread('img_one_piece.jpg')
#create a mask
mask=np.zeros(img.shape[:2],np.uint8)
mask[200:400,250:500]=255
masked_img=cv.bitwise_and(img,img,mask=mask)
59
BEC18L11 Open CV-Python For Digital Image Processing
hist_full=cv.calcHist([img],[0],None,[256],[0,256])
hist_mask=cv.calcHist([img],[0],mask,[256],[0,266])
plt.subplot(221),plt.imshow(img,'gray')
plt.subplot(222),plt.imshow(mask,'gray')
plt.subplot(223),plt.imshow(masked_img,'gray')
plt.subplot(224),plt.plot(hist_full),plt.plot(hist_mask)
plt.xlim([0,256])
plt.show()
60
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
Histogram:
Histogram Equilizer:
61
BEC18L11 Open CV-Python For Digital Image Processing
62
BEC18L11 Open CV-Python For Digital Image Processing
RESULT:
Thus, the program for histograms of an image is executed using openCV – python and
the output is verified successfully.
63
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
FOURIER TRANSFORMS OF AN IMAGE
EXP NO.: 12
AIM:
To write a program in python using openCV functions for fourier transforms of an image
using filters and to get the output using openCV.
THEORY:
Fourier Transform is used to analyze the frequency characteristics of various filters. For
images, 2D Discrete Fourier Transform (DFT) is used to find the frequency domain. A fast
algorithm called Fast Fourier Transform (FFT) is used for calculation of DFT.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
64
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
FFT:
import numpy as np
import cv2
from matplotlib import pyplot as
plt img =
cv2.imread('img_aot.jpg',0)
plt.subplot(121),plt.imshow(img)
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(magnitude_spectrum)
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
IFFT:
import cv2
import numpy as np
from matplotlib import pyplot as
plt img =
cv2.imread('img_aot.jpg',0)
f = np.fft.fft2(img)
65
BEC18L11 Open CV-Python For Digital Image Processing
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20*np.log(np.abs(fshift))
rows, cols = img.shape
66
BEC18L11 Open CV-Python For Digital Image Processing
plt.subplot(133),plt.imshow(img_back)
plt.title('Result in JET'), plt.xticks([]), plt.yticks([])
plt.show()
ROI:
import cv2
import numpy as np
from matplotlib import pyplot as plt
image = cv2.imread("img_aot.jpg")
rows, cols, ch = image.shape
roi = image[100: 280, 150: 320]
plt.subplot(121),plt.imshow(image)
plt.title('Original image'), plt.xticks([]),
plt.yticks([])
plt.subplot(122),plt.imshow(roi)
plt.title('ROI'), plt.xticks([]), plt.yticks([])
plt.show()
67
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
FFT:
IFFT:
68
BEC18L11 Open CV-Python For Digital Image Processing
ROI:
RESULT:
Thus, the program for fourier transforms of an image is executed using openCV – python
and the output is verified successfully.
69
BEC18L11 Open CV-Python For Digital Image Processing
DATE:
FEATURE DETECTION AND DESCRIPTION
EXP NO.: 13
AIM:
To write a program in python using openCV functions for feature detection and description
of an image using filters and to get the output using openCV.
THEORY:
A feature detector is an algorithm which takes an image and outputs locations (i.e. pixel
coordinates) of significant areas in your image. An example of this is a corner detector, which
outputs the locations of corners in your image but does not tell you any other information about
the features detected.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
70
BEC18L11 Open CV-Python For Digital Image Processing
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
PROGRAM:
import cv2
import numpy as np
filename = 'img_fairy_tail.jpg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)
71
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
RESULT:
Thus, the program for feature detection and description of an image is executed using
openCV – python and the output is verified successfully.
72
BEC18L11 Open CV-Python For Digital Image Processing
AIM:
To write a program in python using openCV functions for camera calibration and 3D
reconstuction of an image using filters and to get the output using openCV.
THEORY:
The functions in this section use a so-called pinhole camera model. In this model, a scene view is
formed by projecting 3D points into the image plane using a perspective transformation.
Thus, if an image from the camera is scaled by a factor, all of these parameters should be scaled
(multiplied/divided, respectively) by the same factor. The matrix of intrinsic parameters does not
depend on the scene viewed. So, once estimated, it can be re-used as long as the focal length is
fixed (in case of zoom lens). The joint rotation-translation matrix is called a matrix of
extrinsic parameters. It is used to describe the camera motion around a static scene, or vice versa,
rigid motion of an object in front of a still camera.
PROCEDURE:
Step 1: Download and install the Python 3.9.6 application in your PC with the openCV and
matplotlib library fuctions that is used for digital image processing.
Step 2: Open the IDLE Python window and press CTRL+N to open the new file and start typing
the program.
Step 3: Save the program using the .py extension in the path in which we have installed python.
Also the image should be saved in the same folder of saved program. If not we have to enter the
path of which we have saved the image.
73
BEC18L11 Open CV-Python For Digital Image Processing
PROGRAM:
import numpy as np
import cv2
import glob
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
images = glob.glob('img_chess.png')
74
BEC18L11 Open CV-Python For Digital Image Processing
if ret == True:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
imgpoints.append(corners2)
75
BEC18L11 Open CV-Python For Digital Image Processing
OUTPUT:
RESULT:
Thus, the program for camera calibration and 3D reconstruction of an image is executed
using openCV – python and the output is verified successfully.
76