Computer Vision Lab Manual for ECE
Computer Vision Lab Manual for ECE
REGULATION 2021
MANUAL
MANUAL
PREPARED BY: [Link]
NAME:…………………………………………………………………..
ROLL NO:………………………………………………………………
REGISTER NO:………………………………………………………..
CLASS:…………………………………………………………………
CCS338 COMPUTER VISION
LABORATORY EXPERIMENTS:
Software needed:
OpenCV computer vision Library for OpenCV in Python / PyCharm or C++ / Visual Studio or or equivalent
1 OpenCV Installation and working with Python
2 Basic Image Processing - loading images, Cropping, Resizing, Thresholding, Contour analysis, Bolb
detection
3 Image Annotation – Drawing lines, text circle, rectangle, ellipse on images
4 Image Enhancement - Understanding Color spaces, color space conversion, Histogram equalization,
Convolution, Image smoothing, Gradients, Edge Detection
5 Image Features and Image Alignment – Image transforms – Fourier, Hough, Extract ORB Image features,
Feature matching, cloning, Feature matching based image alignment
6 Image segmentation using Graphcut / Grabcut
7 Camera Calibration with circular grid
8 Pose Estimation
9 3D Reconstruction – Creating Depth map from stereo images
10 Object Detection and Tracking using Kalman Filter, Camshift
INDEX
LIST OF EXPERIMENTS
3 Image Annotation 8
4 Image Enhancement 10
8 Pose Estimation 23
9 3d Reconstruction 25
Annexure
Exp. No: 1
STUDY OF OPENCV INSTALLATION AND WORKING WITH PYTHON
AIM
To understand the process of installing OpenCV and explore its basic functionalities for
image processing tasks in Python.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
THEORY
Introduction
OpenCV (Open-Source Computer Vision Library) is a widely used library for computer
vision and image processing. It provides tools to perform operations such as image manipulation,
object detection, video analysis, and more. This experiment focuses on understanding the steps to
install OpenCV and its capabilities in Python.
Prerequisites
1. OpenCV
OpenCV is an open-source computer vision library with a comprehensive set of functions for
image and video analysis. It supports multiple programming languages, including Python, C++, and
Java. OpenCV is commonly used in applications like face detection, image recognition, augmented
reality, and robotics.
1
pip install opencv-python
3. For additional functionalities (like GUI support), install opencv-contrib-python:
pip install opencv-contrib-python
b. Verify Installation:
• Reading an Image:
OpenCV provides the [Link]() function to read an image.
• Displaying an Image:
The [Link]() function displays an image in a new window.
• Image Manipulation:
OpenCV offers tools to resize, crop, rotate, and filter images.
• Saving an Image:
Use [Link]() to save images after processing.
RESULT
Thus, the process of installing OpenCV and explore its basic functionalities for image
processing tasks in Python was understood.
2
Exp. No: 2
BASIC IMAGE PROCESSING
AIM
To perform basic image processing tasks, including loading images, cropping, resizing,
thresholding, contour analysis, and blob detection using OpenCV.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
Loading an Image
import cv2
image=[Link]("C:/Users/SINDHU/Pictures/[Link]")
# Convert to grayscale
gray_image = [Link](image, cv2.COLOR_BGR2GRAY)
# Save the grayscale image
[Link]('image',gray_image)
# To hold the window on screen, we use [Link] method
[Link](0)
[Link]()
3
OUTPUT
Cropping of an Image
import cv2
image=[Link](‘C:/Users/SINDHU/Pictures/[Link]’)
# Cropping an image
cropped_image = image[80:280, 150:330]
# Display cropped image
[Link]('cropped_image',cropped_image)
[Link](0)
[Link]()
OUTPUT
Resizing of an Image
import cv2
image=[Link]("C:/Users/SINDHU/Pictures/[Link]")
# Resize the image to 300x200
resized_image = [Link](image, (300, 200))
# Save the resized image
[Link]('resized image',resized_image )
[Link](0)
[Link]()
4
OUTPUT
Thresholding of an Image
import cv2
image=[Link]("C:/Users/SINDHU/Pictures/[Link]")
# Apply thresholding
_,thresh_image = [Link](image, 127, 255, cv2.THRESH_BINARY)
# Save the thresholded image
[Link]('thresh_image',thresh_image)
[Link](0)
[Link]()
OUTPUT
import cv2
import matplotlib
image=[Link]("C:/Users/SINDHU/Pictures/[Link]")
# Convert to grayscale
gray = [Link](image, cv2.COLOR_BGR2GRAY)
# Perform thresholding
_, thresh = [Link](gray, 127, 255, cv2.THRESH_BINARY)
# Find contours
contours, _ = [Link](thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
5
# Draw contours on a copy of the original image
contour_image = [Link]()
[Link](contour_image, contours, -1, (0, 255, 0), 2)
# Display the result
[Link]('Contour Image', contour_image)
[Link](0)
[Link]()
OUTPUT
import cv2
import numpy as np
# Filter by area
[Link] = True
[Link] = 100 # Minimum area of the blob
[Link] = 2000 # Maximum area of the blob
# Filter by circularity
[Link] = True
[Link] = 0.7 # Adjust based on requirements
# Filter by convexity
[Link] = True
[Link] = 0.8
6
# Create a SimpleBlobDetector
detector = cv2.SimpleBlobDetector_create(params)
# Detect blobs
keypoints = [Link](image)
OUTPUT
RESULT
Thus, the basic image processing tasks, including loading images, cropping, resizing,
thresholding, contour analysis, and blob detection using OpenCV, have been executed, and the output
was verified.
7
Exp. No: 3
IMAGE ANNOTATION
AIM
To perform basic Image Annotation including drawing lines, text circle, rectangle and ellipse
on images using OpenCV.
HAEDWARE REQUIRED
Personal Computer
SOFTWAREBREQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
import numpy as np
# Draw a Line
[Link](image, (50, 50), (450, 50), (255, 0, 0), thickness=2) # Blue line
# Draw a Rectangle
[Link](image, (100, 100), (400, 200), (0, 255, 0), thickness=3) # Green rectangle
[Link](image, (150, 250), (350, 350), (0, 0, 255), thickness=-1) # Filled red rectangle
# Draw a Circle
[Link](image, (250, 400), 50, (255, 255, 0), thickness=3) # Cyan circle
[Link](image, (400, 400), 30, (0, 255, 255), thickness=-1) # Filled yellow circle
# Draw an Ellipse
[Link](image, (250, 250), (100, 50), 30, 0, 360, (128, 0, 128), thickness=2) # Purple ellipse
# Add Text
8
[Link](image, 'OpenCV Drawing', (120, 480), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0),
thickness=2)
[Link](0)
[Link]()
OUTPUT
RESULT
Thus, the basic Image Annotation including drawing lines, text circle, rectangle and ellipse on
images using OpenCV, have been executed, and the output was verified.
9
Exp. No: 4
IMAGE ENHANCEMENT
AIM
HAEDWARE REQUIRED
Personal Computer
SOFTWAREBREQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Load an image
image = [Link]('C:/Users/SINDHU/Pictures/[Link]') # Replace with your image path
10
[Link]('Histogram Equalized Image', equalized_image)
# 4. Image Smoothing
# Apply Gaussian Blur
gaussian_blur = [Link](image, (5, 5), 0)
[Link]('Gaussian Blur', gaussian_blur)
# 5. Gradients
# Sobel Gradient (X and Y)
sobelx = [Link](gray_image, cv2.CV_64F, 1, 0, ksize=3)
sobely = [Link](gray_image, cv2.CV_64F, 0, 1, ksize=3)
sobelx = [Link](sobelx)
sobely = [Link](sobely)
[Link]('Sobel X', sobelx)
[Link]('Sobel Y', sobely)
# 6. Edge Detection
edges = [Link](gray_image, 100, 200)
[Link]('Canny Edge Detection', edges)
OUTPUT
11
Original Image Grayscale Image
12
Sobel Image Canny Edge Detected Image
Histogram Image
RESULT
Thus, the Image Enhancement including color space conversion, Histogram equialization,
Convolution, Image smoothing, Gradients, Edge Detection using OpenCV, have been executed, and the
output was verified.
13
Exp. No: 5
IMAGE FEATURES AND IMAGE ALIGNMENT
AIM
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
import numpy as np
from matplotlib import pyplot as plt
# 1. Fourier Transform
gray1 = [Link](image1, cv2.COLOR_BGR2GRAY)
dft = [Link](np.float32(gray1), flags=cv2.DFT_COMPLEX_OUTPUT)
dft_shift = [Link](dft)
magnitude_spectrum = 20 * [Link]([Link](dft_shift[:, :, 0], dft_shift[:, :, 1]))
[Link](figsize=(10, 5))
[Link](1, 2, 1)
14
[Link](gray1, cmap='gray')
[Link]('Original Image (Gray)')
[Link](1, 2, 2)
[Link](magnitude_spectrum, cmap='gray')
[Link]('Magnitude Spectrum')
[Link]()
hough_image = [Link]()
if lines is not None:
for rho, theta in lines[:, 0]:
a = [Link](theta)
b = [Link](theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * (a))
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * (a))
[Link](hough_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
[Link]("Hough Transform Lines", hough_image)
# 4. Feature Matching
bf = [Link](cv2.NORM_HAMMING, crossCheck=True)
matches = [Link](descriptors1, descriptors2)
matches = sorted(matches, key=lambda x: [Link])
# Draw matches
matched_image = [Link](image1, keypoints1, image2, keypoints2, matches[:20], None,
flags=2)
[Link]('Feature Matching', matched_image)
15
# Compute the homography matrix
M, mask = [Link](dst_pts, src_pts, [Link], 5.0)
OUTPUT
16
Feature Matching
Aligned Image
RESULT
Thus, the implementation of various image processing techniques like image feature, matching
and alignment using OpenCV was successfully completed.
17
Exp. No: 6
IMAGE SEGMENTATION USING GRABCUT
AIM
To implement image segmentation using the GrabCut algorithm in OpenCV to extract the
foreground object from the background in an image.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
import numpy as np
from matplotlib import pyplot as plt
18
# Step 4: Process the mask
# The mask has values: 0 (background), 1 (probably background), 2 (foreground), 3 (probably
foreground)
# We convert the mask to binary, where 0 and 1 are background, and 2 and 3 are foreground.
binary_mask = [Link]((mask == 2) | (mask == 0), 0,1).astype('uint8')
# Display results
[Link]("Original Image", original_image)
[Link]("Segmented Image", segmented_image)
[Link](0)
[Link]()
OUTPUT
19
RESULT
Thus, the GrabCut algorithm was successfully implemented for image segmentation and the
output was verified.
20
Exp. No: 7
CAMERA CALIBRATION WITH CIRCULAR GRID
AIM
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
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 = [Link]('C:/Users/SINDHU/Pictures/[Link]')
21
# If found, add object points, image points (after refining them)
if ret == True:
[Link](objp)
[Link](0)
[Link]()
OUTPUT
RESULT
Thus, the camera calibration with circular grid operation using OpenCV has been
implemented and the output was verified.
22
Exp. No: 8
POSE ESTIMATION
AIM
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
import numpy as np
# Define the 3D model points of the object (in the object's coordinate space)
# These correspond to key landmarks on the object (e.g., corners of a cube, facial landmarks, etc.)
object_points = [Link]([(0.0, 0.0, 0.0),(0.0, 1.0, 0.0),(1.0, 1.0, 0.0),(1.0, 0.0, 0.0)],
dtype=np.float32)
# Define the 2D image points (these are detected landmarks in the image)
image_points = [Link]([(320, 240),(320, 340),(420, 340),(420, 240)], dtype=np.float32)
23
camera_matrix, dist_coeffs)
if success:
print("Rotation Vector:\n", rotation_vector)
print("Translation Vector:\n", translation_vector)
OUTPUT
RESULT
Thus the camera calibration using a circular grid pattern in OpenCV has been implemented
and the output was verified.
24
Exp. No: 9
3D RECONSTRUCTION
AIM
To perform 3D reconstruction by creating a depth map from stereo image pairs, enabling the
estimation of scene depth and spatial structure using OpenCV.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
import numpy as np
25
right_image = right_image.astype(np.uint8)
stereo = cv2.StereoSGBM_create(minDisparity=min_disp,numDisparities=num_disp,blockSize=
block_size,P1=8 * 3 * block_size**2,P2=32 * 3 * block_size**2,disp12MaxDiff=1,
uniquenessRatio=15,speckleWindowSize=100,speckleRange=32,preFilterCap=63)
create_depth_map(left_image_path, right_image_path)
OUTPUT
image 1 image 2
26
Disparity Map
RESULT
Thus, the 3D reconstruction by creating a depth map from stereo image pairs, enabling the
estimation of scene depth and spatial structure using OpenCV, have been executed, and the output was
verified.
27
Exp. No: 10
OBJECT DETECTION USING KALMAN FILTER
AIM
To perform the object detection with the help of Kalman filtering technique using OpenCV.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
import numpy as np
def object_detection_kalman():
# Initialize video capture
cap = [Link]('C:/Users/SINDHU/Pictures/objdete.mp4') # Change to video file
path if needed
# Initialize VideoWriter
28
fourcc = cv2.VideoWriter_fourcc(*'XVID') # Codec
out = [Link]('C:/Users/SINDHU/Pictures/output_tracking.avi', fourcc, fps, (width,
height))
while [Link]():
ret, frame = [Link]()
if not ret:
break
[Link]()
[Link]()
29
if __name__ == "__main__":
object_detection_kalman()
OUTPUT
RESULT
Thus, the object detection with the help of Kalman filter using OpenCV, has been executed,
and the output was verified.
30
Exp. No: 11
REAL-TIME EDGE DETECTION USING CANNY
AIM
To perform real-time edge detection using the Canny Edge Detection algorithm, enabling the
identification of edges using OpenCV.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
def nothing(x):
pass
# Initialize webcam
cap = [Link](0)
while True:
ret, frame = [Link]()
if not ret:
break
# Convert to grayscale
gray = [Link](frame, cv2.COLOR_BGR2GRAY)
31
# Get trackbar positions
min_thresh = [Link]('Min Threshold', 'Edge Detection')
max_thresh = [Link]('Max Threshold', 'Edge Detection')
# Display results
[Link]('Edge Detection', edges)
if [Link](1) & 0xFF == ord('q'):
break
[Link]()
[Link]()
OUTPUT
RESULT
Thus, the real-time edge detection using the Canny Edge Detection algorithm, enabling the
identification of edges using OpenCV, has been executed, and the output was verified.
32
Exp. No: 12
OBJECT DETECTION USING HAAR CASCADES
AIM
To perform the object detection using Haar cascades, enabling the identification and
localization of specific objects, such as faces or eyes using OpenCV.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM CODE
import cv2
cap = [Link](0)
while True:
ret, frame = [Link]()
if not ret:
break
33
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex, ey, ew, eh) in eyes:
[Link](roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
[Link]()
[Link]()
OUTPUT
RESULT
Thus, the object detection using Haar cascades, enabling the identification and localization of
specific objects, such as faces or eyes using OpenCV, has been executed, and the output was verified.
34
Exp. No: 13
REAL-TIME HAND GESTURE RECOGNITION
AIM
To perform the object detection with the help of Kalman filtering technique using OpenCV.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM
import cv2
import numpy as np
import math
while True:
ret, frame = [Link]()
if not ret:
break
35
# Create a mask for skin detection
mask = [Link](roi_hsv, lower_skin, upper_skin)
36
# Draw contours and hull
[Link](roi, [max_contour], -1, (255, 0, 0), 2)
[Link](roi, [[Link](max_contour)], -1, (0, 255, 0), 2)
# Release resources
[Link]()
[Link]()
OUTPUT
RESULT
Thus, the object detection with the help of Kalman filtering technique using OpenCV has
been implemented and the output was verified.
37
Exp. No: 14
IMAGE REGION SELECTOR
AIM
To perform the Image Region Selector using ROI technique using OpenCV.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM
import cv2
38
# Save the extracted ROI
output_path = "extracted_object.jpg"
[Link](output_path, roi)
OUTPUT
RESULT
Thus, the Image Region Selector using ROI technique in OpenCV has been implemented and
the output was verified.
39
Exp. No: 15
ACCESS IMAGE PROPERTIES
AIM
To understand how to access and analyze the fundamental properties of an image using
OpenCV, including dimensions, number of channels, size, and data type.
HAEDWARE REQUIRED
Personal Computer
SOFTWARE REQUIRED
Pycharm
PROCEDURE
1. Open PyCharm.
2. Click on File → New Project.
3. Set the project name.
4. Choose the base interpreter (Python) and click Create.
5. Replace 'your_image_path.jpg' with the path to your image file.
6. Type the program
7. Run the program by clicking the Run button in PyCharm.
PROGRAM
import cv2
def access_image_properties(image_path):
# Load the image
image = [Link](image_path)
if image is None:
print("Image not found. Please check the file path.")
return
40
print(f" - Size: {size} bytes")
print(f" - Data Type: {data_type}")
OUTPUT
RESULT
Thus, the fundamental properties of an image using OpenCV has been implemented and the
output was verified.
41
ANNEXURE
Expected Viva-Voce Questions
42
20. Why is a circular grid used in camera calibration?
o It provides better accuracy for detecting grid points compared to a square grid.
21. What is pose estimation?
o Determining the position and orientation of an object or camera in 3D space.
22. What role does the PnP algorithm play in pose estimation?
o It estimates the pose from 2D-3D correspondences.
23. What is a depth map?
o A grayscale image where pixel intensity represents the depth of an object from the
camera.
24. How do you compute a depth map from stereo images?
o Using [Link] or [Link].
25. What is the Kalman filter?
o A predictive model used to estimate the state of a moving object from noisy data.
26. What is Camshift?
o Camshift (Continuously Adaptive Mean Shift) is a tracking algorithm used for object
tracking based on histograms.
27. What is the difference between detection and tracking?
o Detection identifies an object, while tracking follows its movement across frames.
43