divide image into two equal parts python opencv

Issue

can someone tell me how to implement a bisection of the image into upper and lower part? so that I could overlap them. for example, I have an image and I should divide it to calculate a number of pixels on each part. I am new to OpenCV and don’t exactly understand the geometry of the image.

Solution

You can crop the top and bottom portion of the image down the middle horizontally.

Open the image.

import cv2
import numpy as np
image = cv2.imread('images/blobs1.png')
cv2.imshow("Original Image", image)
cv2.waitKey(0) 

Use image.shape to let us capture the height and width variables.

height, width = image.shape[:2]
print image.shape

Now we can start cropping.

# Let's get the starting pixel coordiantes (top left of cropped top)
start_row, start_col = int(0), int(0)
# Let's get the ending pixel coordinates (bottom right of cropped top)
end_row, end_col = int(height * .5), int(width)
cropped_top = image[start_row:end_row , start_col:end_col]
print start_row, end_row 
print start_col, end_col

cv2.imshow("Cropped Top", cropped_top) 
cv2.waitKey(0) 
cv2.destroyAllWindows()

# Let's get the starting pixel coordiantes (top left of cropped bottom)
start_row, start_col = int(height * .5), int(0)
# Let's get the ending pixel coordinates (bottom right of cropped bottom)
end_row, end_col = int(height), int(width)
cropped_bot = image[start_row:end_row , start_col:end_col]
print start_row, end_row 
print start_col, end_col

cv2.imshow("Cropped Bot", cropped_bot) 
cv2.waitKey(0) 
cv2.destroyAllWindows()

Finally, we can use image.size to give use the number of pixels in each part.

cropped_top.size
cropped_bot.size

You can do the same thing with contours but it will involve bounding boxes.

Answered By – avereux

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.