CV Lab 1
CV Lab 1
TECHNOLOGY, NAWABSHAH
PRACTICAL MANUALS
Computer Vision
For
21 BS(AI) BATCH
Name: _____________________________________
Batch: ______________________________________
Department: _________________________________
Name: _____________________________ Roll No: __________________________________
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.
OpenCV is a pre-built, open-source CPU-only library (package) that is widely used for
computer vision, machine learning, and image processing applications.
OR
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
# cv2.imread(path_to_image_with_file_extension, flag)
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.
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
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
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()
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()
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
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)
import cv2
import matplotlib.pyplot as plt
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()