Open In App

Dividing Images Into Equal Parts Using OpenCV In Python

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Image Used:

Python3




import cv2
 
img = cv2.imread('img.jpg')
 
# cv2.imread() -> takes an image as an input
h, w, channels = img.shape
 
half = w//2
 
 
# this will be the first column
left_part = img[:, :half]
 
# [:,:half] means all the rows and
# all the columns upto index half
 
# this will be the second column
right_part = img[:, half:] 
 
# [:,half:] means all the rows and all
# the columns from index half to the end
# cv2.imshow is used for displaying the image
cv2.imshow('Left part', left_part)
cv2.imshow('Right part', right_part)
 
# this is horizontal division
half2 = h//2
 
top = img[:half2, :]
bottom = img[half2:, :]
 
cv2.imshow('Top', top)
cv2.imshow('Bottom', bottom)
 
# saving all the images
# cv2.imwrite() function will save the image
# into your pc
cv2.imwrite('top.jpg', top)
cv2.imwrite('bottom.jpg', bottom)
cv2.imwrite('right.jpg', right_part)
cv2.imwrite('left.jpg', left_part)
cv2.waitKey(0)


Output:

Explanation:

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: 

cv2.imwrite('name_of_the_image.jpg',left_part)

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. 



Last Updated : 27 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads