I'm fairly new to python and am struggling with a problem where I already spend quite some time on.
I work on detecting the object in an image and return a clipped version of it (using the SAM model). It works fine with one exception: I cannot get rid of the black background in the jpg file.
def segment_object(jpeg_base64, detected_object, predictor):
jpeg_data = base64.b64decode(jpeg_base64)
nparr = np.frombuffer(jpeg_data, np.uint8)
image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
predictor.set_image(image)
bounding_poly = detected_object["bounding_poly"]["normalizedVertices"]
image_width, image_height = image.shape[1], image.shape[0]
vertices = [
(int(vertex["x"] * image_width), int(vertex["y"] * image_height))
for vertex in bounding_poly
]
input_box = np.array(
[
min(vertices, key=lambda t: t[0])[0],
min(vertices, key=lambda t: t[1])[1],
max(vertices, key=lambda t: t[0])[0],
max(vertices, key=lambda t: t[1])[1],
]
)
masks, _, _ = predictor.predict(
point_coords=None,
point_labels=None,
box=input_box[None, :],
multimask_output=False,
)
# Create a new image with a white background
white_background = np.zeros_like(image, dtype=np.uint8)
white_background[:] = (255, 255, 255)
# Apply the mask returned by the predictor directly
masked_image = cv2.bitwise_and(image, image, mask=masks[0].astype(np.uint8)) **works fine**
# Combine the masked image and the white background
not_mask = cv2.bitwise_not(masks[0].astype(np.uint8)) **issue**
masked_white_background = cv2.bitwise_and(white_background, white_background, mask=not_mask)
clipped_image = cv2.add(masked_image, masked_white_background)
# Convert the OpenCV image to a PIL image and save it as a JPEG in a BytesIO object
pil_image = Image.fromarray(cv2.cvtColor(clipped_image, cv2.COLOR_BGR2RGB))
jpeg_buffer = io.BytesIO()
pil_image.save(jpeg_buffer, format='JPEG')
jpeg_bytes = jpeg_buffer.getvalue()
# Encode the JPEG bytes as base64
clipped_jpeg_base64 = base64.b64encode(jpeg_bytes).decode()
return {
'original_image': image_to_base64(image),
'mask': image_to_base64(masks[0].astype(np.uint8)),
'masked_image': image_to_base64(masked_image),
'masked_white_background': image_to_base64(masked_white_background),
'clipped_image': clipped_jpeg_base64
}
More specifically: The prediction works, the masked_image is returned (but with black background). My idea is to use the inverted mask to make the rest white. However it won't work, the masked_white_background and clipped_image both return a completely white jpg file.
Has anyone an idea what the reason might be?
The issue seems to be this line
masked_white_background = cv2.bitwise_and(white_background, white_background, mask=not_mask)
OpenCV docs says that bitwise_and
returns the conjunction of two input arrays where the keyword argument mask
evaluates to true. So what you're essentially getting is the bitwise and of two white backgrounds.