Region of Interest opencv python

Okay, On further analysis realized that the cv2 since it has been supporting numpy array structure, there is no longer any need for a API, the entire image can be manipulated in the array itself. eg:

img = cv2.imread('image.png')
img = img[c1:c1+25,r1:r1+25]

Here c1 is the left side column pixel location, and r1 is the corresponding row location. And img now has the image specified within the pixels as the ROI.

EDIT: Very nicely explained here, How to copy a image region using opencv in python?


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


As mentioned in documentation, and regarding the error message you got, you rather need to import the appropriate module and then call SetImageROI() method:

import cv
cv.SetImageROI(imag, rect)