Region of Interest opencv python

前端 未结 3 2015
余生分开走
余生分开走 2020-12-06 00:55

I am trying to get a region of an image (ROI) using opencv python. The version of opencv used is 2.4.3. However when I try to call the API

cv2.SetImageROI


        
相关标签:
3条回答
  • 2020-12-06 01:51

    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

    0 讨论(0)
  • 2020-12-06 01:56

    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)
    
    0 讨论(0)
  • 2020-12-06 02:01

    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?

    0 讨论(0)
提交回复
热议问题