Here's a visualization for selecting a ROI from an image
-------------------------------------------
| |
| (x1, y1) w |
| ------------------------ |
| | | |
| | | |
| | ROI | h |
| | | |
| | | |
| | | |
| ------------------------ |
| (x2, y2) |
| |
| |
| |
-------------------------------------------
Consider (0,0)
as the top-left corner of the image with left-to-right as the x-direction and top-to-bottom as the y-direction. If we have (x1,y1)
as the top-left and (x2,y2)
as the bottom-right vertex of a ROI, we can use Numpy slicing to crop the image with:
ROI = image[y1:y2, x1:x2]
But normally we will not have the bottom-right vertex. In typical cases we will most likely have the ROI's bounding box (x,y,w,h)
coordinates obtained from cv2.boundingRect()
when iterating through contours
cnts = cv2.findContours(grayscale_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
ROI = image[y:y+h, x:x+w]
Since OpenCV v2.2, Numpy arrays are naively used to display images. This Numpy slicing method to extract the ROI may not work with older versions