Image Processing with Python and CV2
First thing first what is Cv2 ?
OpenCV is a great tool for image processing and performing computer vision tasks. It is an open-source library that can be used to perform tasks like face detection, objection tracking, landmark detection, and much more. It supports multiple languages including python, java C++.
How to install CV2 ?
In Terminal : pip install opencv-python
Image Processing :
This will import ‘Cv2’ so that we can use in our project :
imread() : imread() method loads an image from the specified file. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix.
Here, I am reading my image named ‘Pic.png’ and storing into the variable image. (sorry, i guess that was obvious with ‘imread’ method 😅 )
Before, next step let’s understand what is ‘Ndarray’ & How images are represented as Ndarray in system ?
What is Ndarry ?
An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. The number of dimensions and items in an array is defined by its shape , which is a tuple of N non-negative integers that specify the sizes of each dimension.
How images are represented as Ndarray in system ?
print(type(image)) : This will give us the datatype of our image variable.
print(image.ndim) : This will give the dimension of our image variable.
Resizing image
cv2.resize : resize() function of OpenCV library cv2. Resizing, by default, does only change the width and height of the image.
We are giving our ‘image’ variable which have our ‘Pic.png’ and changing width and length to half of our original image.
int(image.shape[1]/2) : This will take first index ([1]) and divide it by 2 by after getting image.shape and covert into integer (int) and that gives us width.
int(image.shape[0]/2) : This will take first index ([0]) and divide it by 2 by after getting image.shape and covert into integer (int) and that gives us length.
cv2. imwrite()
cv2. imwrite() method is used to save an image to any storage device. This will save the image according to the specified format in current working directory.
Syntax: cv2.imwrite(filename, image)
cv2. imshow()
cv2.imshow() method is used to display an image in a window. The window automatically fits to the image size.
cv2.waitKey(0)
waitKey(0) will display the window infinitely until any keypress (it is suitable for image display)
cv2. destroyAllWindows()
waitKey() is a keyboard binding function. Its argument is the time in milliseconds. 0 — wait indefinitely cv2. destroyAllWindows() simply destroys all the windows we created.