0% found this document useful (0 votes)
80 views23 pages

AI For CV Labmanual

Uploaded by

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

AI For CV Labmanual

Uploaded by

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

Prestige Institute of Engineering, Management

& Research, Indore

Department of Artificial Intelligence and Data Science

Lab Manual

AD 701
AI for Computer Vision

Name : Kartik Baderiya


Roll No : 0863AD201020
Branch : B. Tech ( AI & DS )
Semester : VII ( 4th year )
Submitted To : Dr. Naveen R Shahi
Prestige Institute of Engineering Research & Management

Lab Date of Faculty


No. Topics to be covered Practical Signature
OpenCV Installation and working with Python
1
Basic Image Processing , loading images, Cropping,
2 Resizing, Thresholding, Contour analysis, Bolb detection

3 Image Annotation – Drawing lines, text circle, rectangle,


ellipse on images

Image Enhancement, Understanding Color spaces, color space


4 conversion, Histogram equialization, Convolution, Image
smoothing, Gradients, Edge Detection
Image Features and Image Alignment – Image transforms –
5 Fourier, Hough, Extract ORB Image features, Feature matching
and cloning

Feature matching based image alignment


6

Image segmentation using Graphcut / Grabcut


7

Camera Calibration with circular grid


8

9 Pose Estimation

10 3D Reconstruction – Creating Depth map from stereo images

pg.
Prestige Institute of Engineering Research & Management

Experiment No.
01 Aim :- OpenCV Installation and working with
Python
Experiment setup :- Install necessary Libraries OpenCV and numpy using pip

pip install opencv-


python pip install
Code:-

import cv2
Output:-
# Load an image
image = cv2.imread('bird.jpg')

# Display the image


cv2.imshow('Image',
image) cv2.waitKey(0)
cv2.destroyAllWindows()

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 02

Aim :- Write a Python script using OpenCV for Basic Image Processing , loading
images, Cropping, Resizing, Thresholding, Contour analysis, Bolb detection.

CODE:-

import cv2
import numpy as
np # Load an
image
image = cv2.imread('bird.jpg')
# Crop a region of interest (ROI)
x, y, w, h = 100, 50, 200, 150 # coordinates of the ROI
roi = image[y:y+h, x:x+w] # image crop to the specified ROI

# Resize the image


resized_image = cv2.resize(image, (300, 200)) # Resizing to
300x200 pixels

# Converting the image to grayscale


gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Applying thresholding
_, thresholded_image = cv2.threshold(gray_image, 127,
255, cv2.THRESH_BINARY)

# Finding contours in the thresholded image


contours, _ = cv2.findContours(thresholded_image,
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Drawing contours on the original image


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

# Blob detection
params =
cv2.SimpleBlobDetector_Params()
params.filterByArea = True
params.minArea = 100
params.filterByCircularity =
True params.minCircularity =
0.7

pg.
Prestige Institute of Engineering Research & Management

detector =
cv2.SimpleBlobDetector_create(params)
keypoints =
detector.detect(thresholded_image)
blob_image = cv2.drawKeypoints(image, keypoints, np.array([]), (0,
0,

pg.
Prestige Institute of Engineering Research & Management

255),

cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Displaying the processed images


cv2.imshow('Original Image',
image) cv2.imshow('Cropped
Image', roi)
cv2.imshow('Resized Image',
resized_image) cv2.imshow('Grayscale
Image', gray_image)
cv2.imshow('Thresholded Image',
thresholded_image) cv2.imshow('Contour
Analysis', image)
cv2.imshow('Blob Detection', blob_image)

Output:-

pg.
Prestige Institute of Engineering Research & Management

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 03

Aim :- Write a python script using OpenCV for Image Annotation – Drawing
lines, text circle, rectangle, ellipse on images
Code:-

import cv2
Output:-
import numpy as np

# Load an image
image = cv2.imread('bird.jpg')

# Drawing a line on the image


cv2.line(image, (50, 50), (200, 200), (0, 255, 0), 2)

# Adding text to the image


cv2.putText(image, 'OpenCV Annotation', (20, 40),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

# Drawing a circle on the image


cv2.circle(image, (300, 150), 50, (255, 0, 0), -1)

# Drawing a rectangle on the image


cv2.rectangle(image, (100, 100), (250, 250), (0, 0, 255), 2)

# Drawing an ellipse on the image


cv2.ellipse(image, (400, 300), (100, 50), 30, 0, 360, (255, 255,
0), -1)

# Displaying the annotated image


cv2.imshow('Annotated Image',
image) cv2.waitKey(0)
cv2.destroyAllWindows()

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 04
Aim :- Write a Python script using OpenCV library for Image Enhancement,
Understanding Color spaces, color space conversion, Histogram equialization,
Convolution, Image smoothing, Gradients, Edge Detection

Code :-

import cv2
import numpy as np

# Load an image
image = cv2.imread('bird.jpg')

# Converting the image to grayscale


gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Histogram equalization for contrast


enhancement equalized_image =
cv2.equalizeHist(gray_image)

# Creating a 5x5 kernel for convolution


kernel = np.ones((5, 5), np.float32) / 25

# Applying convolution for image smoothing


smoothed_image = cv2.filter2D(image, -1, kernel)

# Applying Gaussian blur for additional smoothing


blurred_image = cv2.GaussianBlur(image, (5, 5), 0)

# Calculating image gradients


gradient_x = cv2.Sobel(gray_image, 1, ksize=5
cv2.CV_64F, 0, )
gradient_y = cv2.Sobel(gray_image, 0, ksize=5
cv2.CV_64F, 1, )

# Calculating the magnitude of gradients


gradient_magnitude = cv2.magnitude(gradient_x, gradient_y)

# Performing Canny edge detection


edges = cv2.Canny(gray_image, 100, 200)

# Displaying the enhanced images


cv2.imshow('Original Image', image)
pg.
Prestige Institute of Engineering Research & Management

cv2.imshow('Grayscale Image', gray_image)


cv2.imshow('Histogram Equalization', equalized_image)

pg.
Prestige Institute of Engineering Research & Management

cv2.imshow('Convolution (Smoothing)',
smoothed_image) cv2.imshow('Gaussian Blur',
blurred_image)
cv2.imshow('Gradient Magnitude',
gradient_magnitude) cv2.imshow('Canny Edge
Detection', edges)

Output :-

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 05

Aim :- Write a python script using OpenCV library for Image Features and Image
Alignment – Image transforms – Fourier, Hough, Extract ORB Image features, Feature
matching and cloning

Code :-

import cv2
import numpy as np

# Load two images


image1 = cv2.imread('bird.jpg',
cv2.IMREAD_GRAYSCALE) image2 =
cv2.imread('bird2.jpg', cv2.IMREAD_GRAYSCALE)

# Perform Fourier
Transform f1 =
np.fft.fft2(image1)
fshift1 = np.fft.fftshift(f1)
magnitude_spectrum1 = np.log(np.abs(fshift1))

f2 = np.fft.fft2(image2)
fshift2 = np.fft.fftshift(f2)
magnitude_spectrum2 = np.log(np.abs(fshift2))

# Perform Hough Transform


edges = cv2.Canny(image1, 100, 200)
lines = cv2.HoughLines(edges, 1, np.pi / 180, 100)

# Extract ORB features and perform feature


matching orb = cv2.ORB_create()
keypoints1, descriptors1 = orb.detectAndCompute(image1,
None) keypoints2, descriptors2 =
orb.detectAndCompute(image2, None)

# Feature matching using Brute-Force Matcher


bf = cv2.BFMatcher(cv2.NORM_HAMMING,
crossCheck=True) matches =
bf.match(descriptors1, descriptors2)
matches = sorted(matches, key=lambda x: x.distance)

# Clone and align images using feature matching

pg.
Prestige Institute of Engineering Research & Management

matched_image = cv2.drawMatches(image1, keypoints1, image2,


keypoints2, matches[:10], outImg=None)

# Display the results

pg.
Prestige Institute of Engineering Research & Management

cv2.imshow('Fourier Transform (Image 1)',


magnitude_spectrum1) cv2.imshow('Fourier Transform
(Image 2)', magnitude_spectrum2) cv2.imshow('Hough
Transform', image1)
cv2.imshow('ORB Feature Matching', matched_image)

cv2.waitKey(0)

Output:-

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 06

Aim :- Write Python script using OpenCV library for Feature matching based image
alignment.

Code:-

import cv2
import numpy as np

# Loading the reference image and the target


image reference_image =
cv2.imread('reference_image.jpg',
cv2.IMREAD_GRAYSCALE)
target_image = cv2.imread('target_image.jpg', cv2.IMREAD_GRAYSCALE)

# Creating an ORB (Oriented FAST and Rotated BRIEF)


detector orb = cv2.ORB_create()

# Finding keypoints and descriptors in the reference and target


images keypoints1, descriptors1 =
orb.detectAndCompute(reference_image, None) keypoints2,
descriptors2 = orb.detectAndCompute(target_image, None)

# Creating a Brute-Force Matcher


bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

# Matching descriptors from both images


matches = bf.match(descriptors1, descriptors2)

# Sorting the matches by distance


matches = sorted(matches, key=lambda x: x.distance)

# Drawing the first 10 matches


matching_result = cv2.drawMatches(reference_image,
keypoints1, target_image, keypoints2, matches[:10],
outImg=None)

# Extracting the matched keypoints


matched_keypoints = [keypoints2[match.trainIdx] for match in
matches]

# Ensuring there are enough keypoints for homography


calculation if len(matched_keypoints) >= 4:
pg.
Prestige Institute of Engineering Research & Management

src_pts = np.float32([keypoint1.pt for keypoint1 in


keypoints1]) dst_pts = np.float32([keypoint2.pt for
keypoint2 in
matched_keypoints])

pg.
Prestige Institute of Engineering Research & Management

# Calculating the transformation matrix using RANSAC


M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,
5.0)

# Warping the reference image to align with the


target image aligned_image =
cv2.warpPerspective(reference_image, M,
(target_image.shape[1], target_image.shape[0))

# Displaying the feature matching result and the


aligned image cv2.imshow('Feature Matching Result',
matching_result)
cv2.waitKey(0)
cv2.destroyAllWindo

Output:-

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 07

Aim :- Write Python script using OpenCV library for Image segmentation using
Graphcut / Grabcut.

Code:-

import cv2
import numpy as np

# Load an image
image = cv2.imread('bird.jpg')

# Creating a mask to specify the region to segment


(initialize as background)
mask = np.zeros(image.shape[:2], np.uint8)

# Defining the region of interest (ROI) for the object to


segment rect = (50, 50, 300, 200) # (x, y, width, height)

# Initializing background and foreground models for


GrabCut bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)

# Applying GrabCut algorithm to segment the object


cv2.grabCut(image, mask, rect, bgdModel,
fgdModel, 5, cv2.GC_INIT_WITH_RECT)

# Modifying the mask to differentiate between background,


foreground, and probable areas
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')

# Multiplying the original image by the mask to extract the


segmented object
segmented_image = image * mask2[:, :, np.newaxis]

# Displaying the segmented object


cv2.imshow('Segmented Image',
segmented_image) cv2.waitKey(0)
cv2.destroyAllWindows()

pg.
Prestige Institute of Engineering Research & Management

Output :-

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 8

Aim :- Write Python script using OpenCV library for Camera Calibration with circular
grid.

Code:-

import numpy as
np import cv2

# Define the number of corners in the circular grid pattern


pattern_size = (4, 11) # 4 circles along the rows and 11
along the columns

# Create an array to store the object points for the grid


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

# Arrays to store object points and image points from all the
images obj_points = [] # 3D points in the real world
img_points = [] # 2D points in image plane

# Load the images of the circular grid


images = [cv2.imread('image1.jpg'), cv2.imread('image2.jpg')]

for image in images:


# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Find the circular grid corners in the


image ret, corners = cv2.findCirclesGrid(
gray, pattern_size, flags=cv2.CALIB_CB_ASYMMETRIC_GRID)

# If found, add object points and image


points if ret:
obj_points.append(objp)
img_points.append(corners)

# Perform camera calibration


ret, mtx, dist, rvecs, tvecs =
cv2.calibrateCamera(obj_points, img_points,
gray.shape[::-1], None, None)

pg.
Prestige Institute of Engineering Research & Management

# Print camera matrix and distortion


coefficients print("Camera Matrix:\n", mtx)
print("Distortion Coefficients:\n", dist)

# Perform undistortion on an example image


undistorted_image = cv2.undistort(images[0], mtx, dist, None,
mtx)

# Display the original and undistorted images


cv2.imshow('Undistorted Image',
undistorted_image) cv2.waitKey(0)

Output:-

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 9

Aim :- Write Python script using OpenCV library for Pose Estimation

Code:-

Output:-

pg.
Prestige Institute of Engineering Research & Management

Experiment No. 10

Aim :- Write Python script using OpenCV library for 3D Reconstruction – Creating
Depth map from stereo images

Code:-
Output:-
import numpy as
np import cv2
from matplotlib import pyplot as plt

# read two input images


imgL =
cv2.imread('imageL.jpg',0) imgR
= cv2.imread('imageR.jpg',0)

# Initiate and StereoBM object


stereo = cv2.StereoBM_create(numDisparities=128,
blockSize=15)

# compute the disparity map


disparity =
stereo.compute(imgL,imgR)
disparity1 =

pg.

You might also like