You are on page 1of 76

BEC18L11 Open CV-Python For Digital Image Processing

RECORD NOTEBOOK

Name : J DHARSHAN

Register No : 191081101606
Degree : B.Tech

Branch : Electronics and Communication Engineering

Year & Section : IV& A

Subject Code BEC19L11


OpenCV – Python for Digital Image
Subject Name
Processing Lab
Regulation 2022 – 2023
1
BEC18L11 Open CV-Python For Digital Image Processing

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

Signature Of Lab-In-Charge Signature Of Head Of Dept.

Submitted for the practical examination held in .

Internal Examiner External Examiner


2
BEC18L11 Open CV-Python For Digital Image Processing

LIST OF
EXPERIMENTS
S.NO. DATE CONTENT PAGE FACULITY
NO. SIGNATURE

1 Image Processing in OpenCV 4-8

2 Changing Color Space 9-11

3 Image Thresholding 12-14

4 15-21
Geometric Transformation of an
Image

5 Smoothing Images 22-28

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.

 cv: Main OpenCV functions, Image processing and vision algorithms.


 cvaux: Auxiliary (experimental) OpenCV functions.
 cxcore: Data structures, linear algebra support, XML support drawing functions and
other algorithms.
 highgui: GUI functions, Image and Video I/O.

IMAGE PROCESSING

Image processing is IMAGE +PROCESSING .

1. Image is a collection of PIXELS.


2. Each pixel is like an array of numbers.
3. These numbers determine the color of the pixel.

4
BEC18L11 Open CV-Python For Digital Image Processing

Different types of images:

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 .

 Number of channels : Defines the dimension of array , each pixel is.


 Depth : Defines the maximum bit size of the number which is stored in the array.

1. BINARY IMAGE
Again, as the name suggests each number associated with the pixel can have just one of the
two possible values.

 Each pixel is a 1 bit number.


 It can take either 0 or 1 as its value.
 0 corresponds to Black
 1 corresponds to White
 Number of channels of a binary Image is 1
 Depth of a binary image is 1(bit)

2. GRAYSCALE IMAGE

 Each pixel is a 8 bit number

 It can take values from 0-255


 Each value corresponds to a shade between black and white( 0 for black and 255 for
white)
 Number of channels for a grayscale image is 1
 Depth of a gray scale image is 8(bits)

3. COLOURED IMAGE (RGB):

5
BEC18L11 Open CV-Python For Digital Image Processing

 Each pixel stores three values:

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

To create an image we need to provide the following details

 Size( height and width)


 Depth
 Number of channels
 And specify the pixel values

For creating an image we need we use the following function:


output=cvCreateImage(cvGetSize(input),IPL_DEPTH_8U,3)

This will create a RGB image (most general case among the three types of images
discussed) without specifying pixel values.

SOME COMMON OPENCV FUNCTIONS

cvCvtColor( input, output, conversion type) { Conv. type :CV_BGR2GRAY


,CV_BGR2HSV}
Saves input image in output pointer in other color space

1. Morphological operations on a image:

There are two different kinds of morphological operations :

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)

Before we threshold the image we need to make a clone of the image.

3. Video Input:

A video is basically a collection of continuous images displayed at a certain rate (generally 30


frames per second).
To extract the frames from video first we need to attach this video to the input stream and
then extract those as and when required.
To attach the video to input stream we use the following function
CvCapture* capture=cvCreateFileCapture("file_name.avi" );
And for extracting frames use the following function:
Ipl Image* input_frame=cvQueryFrame(capture);

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

Use the following command for initiating the camera:


CvCapture *capture=cvCreateCameraCapture(0);

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 can be achieved through


for(int i=0;i<100000000&& capture!=NULL ;i++);

Finally image is captured and stored in variable of type


IplImage*frame=cvQueryFrame(capture);

5. Video input through camera:

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, BGRGray and BGR HSV.
For color conversion, we use the function
cv2.cvtColor(input_image, flag)
where flag determinesthe type of conversion.

For BGR  Gray conversion we use the flags


cv2.COLOR_BGR2GRAY.
Similarly for BGR  HSV, we use the flag
cv2.COLOR_BGR2HSV.

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()

#convert BGR to HSV


hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)

#define range of blue colour in HSV


lower_blue=np.array([110,50,50])
upper_blue=np.array([130,255,255])

#Threshold the HSV image to get only red colors


mask=cv2.inRange(hsv,lower_blue,upper_blue)

#Bitwise-AND mask and original image


res=cv2.bitwise_and(frame,frame,mask=mask)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('res',res)
k=cv2.waitKey(5) & 0xFF

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')

retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY)


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

retval2, threshold2 = cv2.threshold(grayscaled, 12,255,cv2.THRESH_BINARY)


gaus = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 115, 1)

retval2, otsu = cv2.threshold(grayscaled, 125,255,cv2.THRESH_BINARY +


cv2.THRESH_OTSU)

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

DATE: GEOMETRIC TRANSFORMATIONS OF


AN IMAGE
EXP NO.: 04

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')

height, width = img.shape[:2]


res = cv2.resize(img,(2*width, 2*height), interpolation = cv2.INTER_CUBIC)

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.

Step 4: Run the program.

Step 5: The output will be obtained in the respective window.

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

DATE: MORPHOLOGICAL TRANSFORMATION OF


EXP NO.: 06 IMAGES

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.

Step 4: Run the program.

Step 5: The output will be obtained in the respective window.

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.

1. Sobel and Scharr Derivatives

Sobel operators is a joint Gausssian smoothing plus differentiation operation, so it is more


resistant to noise. You can specify the direction of derivatives to be taken, vertical or horizontal
(by the arguments, yorder and xorder respectively). You can also specify the size of kernel by the
argument ksize. If ksize = -1, a 3x3 Scharr filter is used which gives better results than 3x3 Sobel
filter. Please see the docs for kernels used.

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.

Step 4: Run the program.

Step 5: The output will be obtained in the respective window.

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.

Step 5: Run the program.

Step 6: The output will be obtained in the respective window.


43
BEC18L11 Open CV-Python For Digital Image Processing

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.

Step 4: Run the program.

Step 5: The output will be obtained in the respective window.

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]

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


size = (gaussian_pyramid[i - 1].shape[1], gaussian_pyramid[i - 1].shape[0])
gaussian_expanded = cv2.pyrUp(gaussian_pyramid[i], dstsize=size)
laplacian = cv2.subtract(gaussian_pyramid[i - 1], gaussian_expanded)

47
BEC18L11 Open CV-Python For Digital Image Processing

laplacian_pyramid.append(laplacian)
cv2.imshow(str(i), laplacian)

cv2.imshow("Original image", img)


cv2.waitKey(0)

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))

footbase_ball = np.hstack((img1[:, :500], img2[:, 500:])) # Gaussian Pyramid 1


layer = img1.copy()
gaussian_pyramid = [layer]

for i in range(6):
layer = cv2.pyrDown(layer)
gaussian_pyramid.append(layer)

# Laplacian Pyramid 1
layer = gaussian_pyramid[5]
laplacian_pyramid = [layer]

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


size = (gaussian_pyramid[i - 1].shape[1], gaussian_pyramid[i - 1].shape[0])
gaussian_expanded = cv2.pyrUp(gaussian_pyramid[i], dstsize=size)

48
BEC18L11 Open CV-Python For Digital Image Processing

laplacian = cv2.subtract(gaussian_pyramid[i - 1], gaussian_expanded)


laplacian_pyramid.append(laplacian)

# 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]

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


size = (gaussian_pyramid2[i - 1].shape[1], gaussian_pyramid2[i - 1].shape[0])
gaussian_expanded = cv2.pyrUp(gaussian_pyramid2[i], dstsize=size)
laplacian = cv2.subtract(gaussian_pyramid2[i - 1], gaussian_expanded)
laplacian_pyramid2.append(laplacian)

# Laplacian Pyramid Footbase_ball


footbase_ball_pyramid = []
n=0

for img1_lap, img2_lap in zip(laplacian_pyramid, laplacian_pyramid2):


n += 1
cols, rows, ch = img1_lap.shape
laplacian = np.hstack((img1_lap[:, 0:int(cols/2)], img2_lap[:, int(cols/2):]))
footbase_ball_pyramid.append(laplacian)

49
BEC18L11 Open CV-Python For Digital Image Processing

# Reconstructed Footbase_ball
footbase_ball_reconstructed = footbase_ball_pyramid[0]

for i in range(1, 6):


size = (footbase_ball_pyramid[i].shape[1], footbase_ball_pyramid[i].shape[0])
footbase_ball_reconstructed = cv2.pyrUp(footbase_ball_reconstructed, dstsize=size)
footbase_ball_reconstructed = cv2.add(footbase_ball_pyramid[i],
footbase_ball_reconstructed)

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.

Step 4: Run the program.

Step 5: The output will be obtained in the respective window.

53
BEC18L11 Open CV-Python For Digital Image Processing

PROGRAM:

import cv2
import matplotlib.pyplot as plt

# read the image


image = cv2.imread("img_blackbull.jpg")

# convert to RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# create a binary thresholded image


_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)

# show it
plt.imshow(binary, cmap="gray")
plt.show()

# find the contours from the thresholded image


contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)

# draw all contours


image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)

# show the image with the drawn contours


plt.imshow(image)

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:

Histogram is considered as a graph or plot which is related to frequency of pixels in an Gray


Scale Image with pixel values (ranging from 0 to 255). Grayscale image is an image in which
thevalue of each pixel is a single sample, that is, it carries only intensity information where pixel
value varies from 0 to 255. Images of this sort, also known as black-and-white, are composed
exclusively of shades of gray, varying from black at the weakest intensity to white at the
strongest where Pixel can be considered as a every point in an image.

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.

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.hist(b.ravel(), 256, [0, 256])


plt.hist(g.ravel(), 256, [0, 256])
plt.hist(r.ravel(), 256, [0, 256])

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.plot(cdf_normalized, color = 'b')


plt.hist(img.flatten(),256,[0,256], color = 'b')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper right')

plt.show()

Histogram using Mask:

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

#calculate histogram with mask and without mask


#check third argument for mask

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

Histogram using Mask:

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.

Step 4: Run the program.

Step 5: The output will be obtained in the respective window.

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)

dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT)


dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))

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

crow,ccol = rows/2 , cols/2


f_ishift = np.fft.ifftshift(fshift)
img_back = np.fft.ifft2(f_ishift)
img_back = np.abs(img_back)

plt.subplot(131),plt.imshow(img, cmap = 'gray')


plt.title('Input Image'), plt.xticks([]), plt.yticks([])

plt.subplot(132),plt.imshow(img_back, cmap = 'gray')


plt.title('Image after HPF'), plt.xticks([]), plt.yticks([])

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.

A feature descriptor is an algorithm which takes an image and outputs feature


descriptors/feature vectors. Feature descriptors encode interesting information into a series of
numbers and act as a sort of numerical "fingerprint" that can be used to differentiate one feature
from another. Ideally this information would be invariant under image transformation, so we
canfind the feature again even if the image is transformed in some way. An example would be
SIFT, which encodes information about the local neighbourhood image gradients the numbers of
the feature vector. Other examples you can read about are HOG and SURF.

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.

Step 4: Run the program.

Step 5: The output will be obtained in the respective window.

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)

#result is dilated for marking the corners, not important


dst = cv2.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv2.imshow('dst',img)

if cv2.waitKey(0) & 0xff == 27:


cv2.destroyAllWindows()

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

DATE: CAMERA CALIBRATION AND 3D


EXP NO.: 14 RECONSTRUCTION

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

Step 4: Run the program.

Step 5: The output will be obtained in the respective window.

PROGRAM:

import numpy as np
import cv2
import glob

# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# prepare object points, like (0,0,0), (1,0,0), (2,0,0)....,(6,5,0)


objp = np.zeros((6*7,3), np.float32)
objp[:,:2] = np.mgrid[0:7,0:6].T.reshape(-1,2)

# 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')

for fname in images:


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

# Find the chess board corners


ret, corners = cv2.findChessboardCorners(gray, (7,6),None)

# If found, add object points, image points (after refining them)

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)

# Draw and display the corners


img = cv2.drawChessboardCorners(img, (7,6), corners2,ret)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

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

You might also like