Search code examples
pythonopencvcrop

How to crop the same ROI in a rectangle with different sizes


I want to crop some regions (ROIs) of images, i am currently extracting from images a rectangle shape and in this shape i want to extract some ROIs that are always in the same local but the rectangle/image will have different resolutions but the same porportion (ID Card porpotion) so i can not use fixed coordenates like i am currently doing:

 ((x1,y1),(x2,y2)) = box.position

 print(box.position)

 cv.rectangle(cvImage, (x1, y1), (x2, y2), (255,0,0), 2)

But this will not work in all images, i think i already made the point :)

How i can use like % or something similar to always get the same spots in the rectangle regardless of resolution/size of the rectangle.

Thank you.


Solution

  • Yes you can always select the same proportions of an image. For instance, extract a rectangle with coordinates defined by a fixed ratio (or percentage)

    img_w = 1000 # = cvImage.width
    img_h = 1000 # = cvImage.height
    tl_x = 10.0 / 100.0
    tl_y = 10.0 / 100.0
    br_x = 90.0 / 100.0
    br_y = 90.0 / 100.0
    
    print (tl_x, tl_y, br_x, br_y)
    
    rect_tl = (int(tl_x * img_w), int(tl_y * img_h))
    rect_br = (int(br_x * img_w), int(br_y * img_h))
    
    print (rect_tl, rect_br)
    
    #cv.rectangle(cvImage, rect_tl, rect_br, (255,0,0), 2)
    

    This will compute the coordinates of a rectangle in an image of size 1000x1000, but it is a variable defined as img_w x img_h

    The hardcoded rectangle is placed with 10% padding, defined using top-left & bottom-right corners

    As expected the output is :

    0.1 0.1 0.9 0.9
    (100, 100) (900, 900)