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
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