How to crop image based on binary mask

后端 未结 5 694
盖世英雄少女心
盖世英雄少女心 2021-02-10 03:27

I am using torch with some semantic segmentation algorithms to produce a binary mask of the segmented images. I would then like to crop the images based on that mask. To be clea

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-10 03:53

    You can use the boundingRect function from opencv to retrieve the rectangle of interest, and you can crop the image to that rectangle. A python implementation would look something like this:

    import numpy as np
    import cv2
    
    mask = np.zeros([600,600], dtype=np.uint8)
    mask[200:500,200:500] = 255                 # set some values to 255 to represent an actual mask
    rect = cv2.boundingRect(mask)               # function that computes the rectangle of interest
    print(rect)
    
    img = np.ones([600,600, 3], dtype=np.uint8) # arbitrary image
    cropped_img = img[rect[0]:(rect[0]+rect[2]), rect[1]:(rect[1]+rect[3])]  # crop the image to the desired rectangle 
    

    substitute mask an img with your own

提交回复
热议问题