0% found this document useful (0 votes)
38 views

CV Lab 1

ukfgfgfgfgfgfgfgfgjkeu
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)
38 views

CV Lab 1

ukfgfgfgfgfgfgfgfgjkeu
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/ 7

QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE &

TECHNOLOGY, NAWABSHAH

DEPARTMENT OF ARTIFICIAL INTELLIGENCE

PRACTICAL MANUALS

FOR ACADEMIC SESSION 2023-2024

Computer Vision

For

21 BS(AI) BATCH

Name: _____________________________________

Roll Number: ________________________________

Batch: ______________________________________

Department: _________________________________
Name: _____________________________ Roll No: __________________________________

Signature of Lab Tutor: ____________________ Date: ________________________________

LAB 1: Computer Vision using OpenCV and Python

Objectives: In this lab, students will be able to learn:

1. Introduction and how to install OpenCV


2. Import OpenCV package
3. Read an image
4. Display an image
5. Convert to grayscale
6. Convert to HSV
7. Save an image
8. Thresholding
9. Eroding and Dilation
10. Edge Detection
11. Contouring Detection

1. Introduction

OpenCV (Open Source Computer Vision): it is one of the most widely used tools for computer
vision and image processing tasks. It is used in various applications such as face detection,
video capturing, tracking moving objects, object disclosure, nowadays in COVID applications
such as face mask detection, social distancing, and many more.

Installing OpenCV Package for Image Pre-processing

OpenCV is a pre-built, open-source CPU-only library (package) that is widely used for
computer vision, machine learning, and image processing applications.

Install the OpenCV package using:

pip install opencv-python

OR

pip install opencv-contrib-python

Run any of these commands on your command line terminal or if you are using Anaconda
Navigator – Jupyter Notebook, you can change “pip” with the “conda” command and install the
same.
2. Importing the Package
We can import the package by calling the “cv2” module like this:

import cv2

3. Reading an Image

OpenCV provides a function cv2.imread() for reading an image.

# cv2.imread(path_to_image_with_file_extension, flag)

The usage code looks like this:

img = cv2.imread("quest.jpg", 1)

The “imread” method of the cv2 package is used to read the image and the first parameter
corresponds to the path of the image with its filename and extension, while the second
parameter is the flag that you can set which tells the way, how to read in the image. The second
parameter is used to specify the color of an image. You can specify this parameter to 0 to read
the image as grayscale, -1 for reading the image as unchanged (reads the image as alpha or
transparency channel if it is there) and 1, as a color image. The default is 1 which is a color
image.

4. Displaying an image

OpenCV provides a function cv2.imshow(), we can display the image in a window. The first
argument which we will pass will be the window name which is a string. The second argument
will be the image.

cv2.imshow(‘image’,img)

When you try to close it, you might feel stuck with its window. So to combat that, we can use a
simple “waitKey” method.
cv2.imshow('QUEST', img)
k = cv2.waitKey(0)
if k == 27 or k == ord('q'):
cv2.destroyAllWindows()
The parameter ‘0’ in the “waitKey” is used to keep the window open until we close it. After
that, we can assign the variable to act for closing the window when we press the ‘ESC’ key or
the key ‘q’. The cv2.destroAllWindows() method is used for closing or deleting the graphical
windows from the screen/memory.

Working Example:

import cv2
img = cv2.imread('F:\\quest.jpg')
if img is not None:
print('hello')
else:
print('not hello')
cv2.imshow('my img',img)
cc = cv2.waitKey(0)
if cc == 27 or cc == ord('q'):
cv2.destroyAllWindows()

5. Convert to grayscale

OpenCV provides a function cvtColor() which is used to convert colored images to grayscale.

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

6. Convert to HSV

HSV is another type of color space in which H stands for hue, S stands for Saturation and V
stands for Value.

A Hue represents color which is the angle from 0 degrees to 360 degrees.

Saturation: It indicates the range of grey in the color space. It ranges from 0 to 100%. The value
is calculated from 0 to 1. When the value is ‘0,’ the color is grey and when the value is ‘1,’ the
color is a primary color.

Value is the brightness of the color and varies with color saturation. It ranges from 0 to 100%.
When the value is ‘0’ the color space will be black. With the increase in the value, the color
space brightness up and shows various colors.

HSV_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

Working Example:

import cv2
import matplotlib.pyplot as plt
image = cv2.imread('F:\QUEST\All_Semesters_2020\Second_Semester\Computer Vision\
cat.png')
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
HSV_img = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(image)

ax2 = fig.add_subplot(2,2,2)
ax2.imshow(gray)

ax3 = fig.add_subplot(2,2,3)

ax3.imshow(HSV_img)
plt.show()

7. Save an image

After converting we can save the image as:

cv2.imwrite(‘gray_cat.jpg', gray)
By default the image will be saved in the current working directory. The first parameter
corresponds to the name of the file in which the image is to be saved and the second parameter
is the variable that contains the image (pixel information).

8. Thresholding

OpenCV provides a function cv2.threshold to apply thresholding on an image. Thresholding is the


simplest method of image segmentation. From a grayscale image, thresholding can be used to create
binary images, where the pixels are either 0 or 255.

Otsu Thresholding
In Otsu Thresholding, a value of the threshold isn’t chosen but is determined automatically.

Working Example:
import cv2
image = cv2.imread('F:\QUEST\All_Semesters_2020\Second_Semester\Computer Vision\
cat.png')
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
ret, thresh1 = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow('Otsu Threshold', thresh1)
cv2.waitKey(0)
cv2.destroyAllWindows()

9. Eroding and Dilation

Erosion and dilation are two fundamental morphological operations. Dilation adds pixels to the
boundaries of objects in an image, while erosion removes pixels on object boundaries.

Working Example:
import numpy as np
import cv2
import matplotlib.pyplot as plt
image = cv2.imread('F:\QUEST\All_Semesters_2020\Second_Semester\Computer Vision\
e_d.png')
kernel = np.ones((3,3),np.uint8)
erosion = cv2.erode(image,kernel,iterations = 1)
dilation = cv2.dilate(image,kernel,iterations = 1)

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(image)

ax2 = fig.add_subplot(2,2,2)
ax2.imshow(erosion)

ax3 = fig.add_subplot(2,2,3)
ax3.imshow(dilation)
plt.show()

10. Edge Detection

The Canny edge detector is an edge detection operator that uses a multi-stage algorithm to
detect a wide range of edges in images.
import cv2

# Read image from disk.


img = cv2.imread(‘FILE_NAME’)

# Canny edge detection.


edges = cv2.Canny(img, 30, 200)

cv2.imshow('Canny edges', edges)


cv2.waitKey(0)
cv2.destroyAllWindows()

11. Contouring Detection


Contours are defined as the line joining all the points along the boundary of an image that are
having the same intensity. The contours are very useful for shape analysis and object detection.
OpenCV provides a findcontour() function that helps in extracting the contours from the image.
Before finding contours, we should apply threshold or canny edge detection. Then, by using
findContours() method, we can find the contours in the binary image. The command for the
usage of findContours()function is as follows:
cv2.findContours(image, mode, method, contours)
The parameters of the findContours() function are as follows:
image: Source, an 8-bit single-channel image.
mode: Contour retrieval mode.
method: Contour approximation method.
The mode parameter’s values are enumerated as follows:
cv2.RETR_EXTERNAL: Retrieves only the extreme outer contours.
cv2.RETR_LIST: Retrieves all of the contours without establishing any hierarchical
relationships.
cv2.RETR_CCOMP: Retrieves all of the contours and organizes them into a two level
hierarchy.
cv2.RETR_TREE: Retrieves all of the contours and reconstructs a full hierarchy of nested
contours.
On the other hand, approximation method can be one from the following:
cv2.CHAIN_APPROX_NONE: Stores absolutely all the contour points.
cv2.CHAIN_APPROX_SIMPLE: Compresses horizontal, vertical, and diagonal segments and
leaves only their end points.

Draw Contour
After detecting the contour vectors, contours are drawn over the original image by using the
cv2.drawContours() function. The command for the cv2.drawContours() function is as follows:
cv2.drawContours(image, contours, contourIdx, color)

The parameters of the drawContours() function are as follows:

image: Destination image.


contours: All the input contours. Each contour is stored as a point vector.
contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
color: Color of the contours.
Working Example:

import cv2
import matplotlib.pyplot as plt

# Read image from disk.


img = cv2.imread(‘file_name’)

# Canny edge detection.


edges = cv2.Canny(img, 30, 200)
contours,hierarchy=cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(edges)

ax2 = fig.add_subplot(2,2,2)
ax2.imshow(img)
plt.show()

You might also like