NumPy/OpenCV 2: how do I crop non-rectangular region?

后端 未结 2 1406
甜味超标
甜味超标 2020-11-27 12:42

I have a set of points that make a shape (closed polyline). Now I want to copy/crop all pixels from some image inside this shape, leaving t

2条回答
  •  北海茫月
    2020-11-27 12:49

    The following code would be helpful for cropping the images and get them in a white background.

    import cv2
    import numpy as np
    
    # load the image
    image_path = 'input image path'
    image = cv2.imread(image_path)
    
    # create a mask with white pixels
    mask = np.ones(image.shape, dtype=np.uint8)
    mask.fill(255)
    
    # points to be cropped
    roi_corners = np.array([[(0, 300), (1880, 300), (1880, 400), (0, 400)]], dtype=np.int32)
    # fill the ROI into the mask
    cv2.fillPoly(mask, roi_corners, 0)
    
    # The mask image
    cv2.imwrite('image_masked.png', mask)
    
    # applying th mask to original image
    masked_image = cv2.bitwise_or(image, mask)
    
    # The resultant image
    cv2.imwrite('new_masked_image.png', masked_image)
    

    Input Image:

    Mask Image:

    Resultant output image:

提交回复
热议问题