Home > OS >  Is there a method in openCV that crops an image and leave the uncropped area in black?
Is there a method in openCV that crops an image and leave the uncropped area in black?

Time:10-13

Hi all as the title said is there a way for this? For example, I want to crop fourth quadrant of an image and the other area will be turned to black while retaining its original size. Currently, I am getting the center width and height of the image then accessing the pixel:

Cropped = I[centerHeight:,centerWidth:]

but that just stores the fourth quadrant cropped image. Thanks!

CodePudding user response:

I don't think there is a function in OpenCV that does that work. This function will solve your problem.

import numpy as np
def crop_image(img, cx, cy, w, h):
    """
    args:
        cx: x coordinate of center
        cy: y coordinate of center
        w: width of crop 
        h: height of crop
    """
    result = np.zeros(img.shape, dtype=np.uint8)
    result[cx - w//2 :cx   w//2, cy - h//2:cy   h//2] = img[cx - w//2 :cx   w//2, cy - h//2:cy   h//2]
    return result
  • Related