Learn Everything about Open CV

Original article was published by Abhayparashar31 on Artificial Intelligence on Medium


Reading, writing, and Showing an image

To read an image using open cv we have a function as imread(), for showing an image we have a function imshow() and for writing, we have a function as imwrite(). Let’s see the syntax of each one.

imread():

img = cv2.imread("PATH_TO_IMAGE.jpg/png")Example
img = imread("images/dog0.jpg")

imshow():

cv2.imshow("WINDOW NAME",IMG_VAR)Example
imshow("Dog Image",img)

imwrite():

cv2.imwrite(FILENAME, IMAGE)
filename: A string representing the file name. The filename must include image format like .jpg, .png, etc.
image: It is the image that is to be saved.
Example
cv2.imwrite('images/img',img)

Reading Video and Integration with the webcam

Reading a video file is much similar to reading an image file in OpenCV. The difference is here we use cv2.videocapture.
Syntax

video = cv2.VideoCapture("FILEPATH.mp4")Example
video = cv2.VideoCapture("video/dog/dog.mp4")

A Video is a collection of many frames joint together, each frame is an image. To see a video using OpenCV we just need to show each frame of the video using a while loop.

while True:
success , img = cap.read()
cv2.imshow("Video",img)
if cv2.waitKey(1) & 0xff==ord('q'):##key 'q' will break the loop
break

To integrate with the webcam we need to pass the port value of the webcam instead of the path to video. If you are using a laptop and don’t have any external webcam connected then simply pass 0 and if you have any external webcam connected then pass one.

cap = cv2.VideoCapture(0)
cap.set(3,640) ## Frame width
cap.set(4,480) ## Frame Height
cap.set(10,100) ## Brightness
while True:
success, img = cap.read()
cv2.imshow("Video",img)
if cv2.waitKey(1) & 0xff == ord('q'):
break

Resizing and Cropping Images

Resizing is a process of changing the shape of an image. In Opencv we can resize the shape of images using the resize function.
Syntax

cv2.resize(IMG,(WIDTH,HEIGHT))
IMG: image which we want to resize
WIDTH: new width of the resize image
HEIGHT: new height of the resize image
Example
cv2.resize(img,(224,224))

To Resize an image first we need to know the shape of the image. we can find the shape of any image using shape Then according to image shape, we can increase the size or decrease the size of the image. Let’s see it by example.

import cv2
img = cv2.imread("images/img0.jpg") ##Choose any image
print(img.shape)
imgResize = cv2.resize(img,(224,224)) ##Decrease size
imgResize2 = cv2.resize(img,(1024,1024)) ##Increase size
cv2.imshow("Image",img)
cv2.imshow("Image Resize",imgResize)
cv2.imshow("Image Increase size",imgResize2)
print(imgResize.shape)
cv2.waitKey(0)

If you don’t want to hardcode the width and height you can also use the shape and then increase the width and height using indexing.

import cv2
img = cv2.imread("images/img0.jpg") ##Choose any image
print(img.shape)
shape = img.shape
imgResize = cv2.resize(img,(shape[0]//2,shape[1]//2))##Decrease size
imgResize2 = cv2.resize(img,(shape[0]*2,shape[1]*2)) ##Increase size
cv2.imshow("Image",img)
cv2.imshow("Image Resize",imgResize)
cv2.imshow("Image Increase size",imgResize2)
print(imgResize.shape)
cv2.waitKey(0)
“Image Resize — Image By Author”

Cropping Image

Cropping is the process of fetching a part of the image. In open cv, we can perform cropping by defining the cropped rectangle coordinates.
Syntax

imgCropped = img[y1:y2, x1:x2](x1,y1): top-left vertex
(x2,y2): bottom-right vertex
Example
imgCropped = img[0:100,200:200]

Using the Crop method let’s try to fetch the face of Monalisa from the image.

import cv2
img = cv2.imread("images/img0.jpg")
imgCropped = img[50:250,120:330]
cv2.imshow("Image cropped",imgCropped)
cv2.imshow("Image",img)
cv2.waitKey(0)
“Cropping Image — Image By Author

You can also use paint to find the correct coordinate for (x1,y1),(x2,y2).

Right Click on the image and save it, Try to fetch the King card From the image.

Hint: Use paint to find the correct coordinates and at the end, use resize to increase the size of the cropped image.

“Try to Do It yourself Before Going for the solution”

Basic image filters using functions

There are many basic filters we can use on our images like converting our image into grayscale, blur image, and more. Let’s see the important ones one by one.

Img to gray

To convert an image into grayscale we can use a function cvtColor and here we pass cv2.COLOR_BGR2GRAY as a parameter.
Syntax

imgGray = cv2.cvtColor(IMG,cv2.CODE)
IMG: Original image
CODE: Conversion code for Gray(COLOR_BGR2GRAY)
Example
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

Img to HSV

To convert an image into HSV we can use a function cvtColor and here we pass cv2.COLOR_BGR2HSV as a parameter. It is mostly used in object tracking.
Syntax

imgGray = cv2.cvtColor(IMG,cv2.CODE)
IMG: Original image
CODE: Conversion code for Gray(COLOR_BGR2HSV)
Example
imgHsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

Blur Image

Blur is used to remove extra noise from the image also called smoothing. It is the process of applying a low pass filter on to an image. To use Blur in Opencv we have a function GaussianBlur.
Syntax

imgBlur = cv2.GaussianBlur(img,(sigmaX,sigmaY),kernalSize)kernalsize − A Size object representing the size of the kernel.
sigmaX − A variable representing the Gaussian kernel standard deviation in X direction.
sigmaY - same as sigmaX
Exmaple
imgBlur = cv2.GaussianBlur(img,(3,3),0)

Edge Detection

In Open cv, we use a canny edge detector to detect edges in images. there are also different edge detectors but the most famous one is the canny edge detector. The canny edge detector is an edge detection operator, that uses a multi-stage algorithm to detect a wide range of edges in an image. It was developed by John F. Canny in the year1986.
Syntax

imgCanny = cv2.Canny(img,threshold1,threshold2)threshold1,threshold2:Different values of threshold different for every imagesExample
imgCanny = cv2.Canny(img,100,150)

Dilation

Dilation is used to increase the size of the edges in the images. First, we define a kernel matrix size of odd numbers(5,5). Then using the kernel we perform Dilation on the image. we apply dilation on the output image of the Canny edge detector.
Syntax

kernel = np.ones((5,5),np.uint8) ## DEFINING KERNEL OF 5x5
imgDialation = cv2.dilate(imgCanny,kernel,iterations=1) ##DIALATION

Erosion

Erosion is just opposite to dilation it is used to decrease the size of the edges in the images. First, we define a kernel matrix size of odd numbers(5,5). Then using the kernel we perform Erosion on the image. we apply erosion on the output image of the Canny edge detector.

kernel = np.ones((5,5),np.uint8) ## DEFINING KERNEL OF 5x5
imgDialation = cv2.erode(imgCanny,kernel,iterations=1) ##EROSION

Now, Apply all the basic functions on the Monalisa image in the same program.