Home > Software design >  How to crop images to remove excess background using image mask?
How to crop images to remove excess background using image mask?

Time:09-14

I have two images of a person standing up: one original RGB image with the person and background and the mask/alpha matte for that image displaying only the silhouette of the person. So far I have been able to remove the excess padding from the masked imaged via cropping using the function below.

def crop_excess(image):
    y_nonzero, x_nonzero = np.nonzero(image)
    return image[np.min(y_nonzero):np.max(y_nonzero), np.min(x_nonzero):np.max(x_nonzero)]

Now I would like to use the cropped mask and impose it on the original RGB image so that the excess background is removed.

Example images

Any ideas on how this could be done?

CodePudding user response:

You should get values from mask and use it on both images

y_nonzero, x_nonzero = np.nonzero(image)

y1 = np.min(y_nonzero)
y2 = np.max(y_nonzero)
x1 = np.min(x_nonzero)
x2 = np.max(x_nonzero)

cropped_image = image[y1:y2, x1:x2]

cropped_original_image = original_image[y1:y2, x1:x2]
  • Related