Dividing Images Into Equal Parts Using OpenCV In Python
In this article, we are going to see how to divide images into equal parts using OpenCV in Python. We are familiar with python lists and list slicing in one dimension. But here in the case of images, we will be using 2D list comprehension since images are a 2D matrix of pixel intensity.
First, select an image as input and read it using the cv2.imread() function. Then extract the dimensions of the image by using img.shape command and store the value into h, w, channels respectively. After that performing list slicing on the image will produce the desired result. Why? As mentioned earlier images are nothing but a 2D matrix of colour pixel intensities. Hence dividing images into two or more parts means basically slicing a matrix into two or more parts.
For horizontal division, we need to divide the width by a factor of 2 and then take the matrix till that index and store it in a variable ‘left_part’ in this case. It goes something like this:
left_part = img[:,:w//2]
After storing the two parts in different variables, we are displaying them using the cv2.imshow() function which takes two arguments 1st, the title of the image which is a string, and 2nd is the image to be displayed. Example:
cv2.imshow('Title of the image', left_part)
To save the resultant image on the computer we use the cv2.imwrite() function which also takes two arguments one is a string and the other is the image to be saved. Example:
The last function cv2.waitKey() takes only one argument that is time in ms. cv2.waitKey(1) means all the cv2.imshow() will display the images for 1ms and then will close the window automatically, whereas cv2.waitKey(0) will display the window till infinity, i.e. unless the user presses exit.