How to copy a image region using opencv in python?

后端 未结 3 1716
悲哀的现实
悲哀的现实 2020-12-02 14:30

I am trying to implement a license plate recognition software using the ideas from http://iamabhik.wordpress.com/category/opencv/.

I implemented the plate location u

3条回答
  •  情书的邮戳
    2020-12-02 15:19

    Here's a visualization for cropping a ROI from an image

    -------------------------------------------
    |                                         | 
    |    (x1, y1)                             |
    |      ------------------------           |
    |      |                      |           |
    |      |                      |           | 
    |      |         ROI          |           |  
    |      |                      |           |   
    |      |                      |           |   
    |      |                      |           |       
    |      ------------------------           |   
    |                           (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 be iterating through contours where the rectangular ROI coordinates can be found with cv2.boundingRect(). Additionally, if we wanted to save multiple ROIs, we could keep a counter

    cnts = cv2.findContours(grayscale_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    
    ROI_number = 0
    for c in cnts:
        x,y,w,h = cv2.boundingRect(c)
        ROI = image[y:y+h, x:x+w]
        cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
        ROI_number += 1
    

    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

提交回复
热议问题