我是 python 的新手,正在努力解决我已经花了很多时间的问题。
我致力于检测图像中的对象并返回它的剪辑版本(使用 SAM 模型)。它工作正常,但有一个例外:我无法摆脱 jpg 文件中的黑色背景。
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
}
更具体地说:预测有效,返回了 masked_image(但背景为黑色)。我的想法是使用倒置遮罩使其余部分变白。然而它不起作用,masked_white_background 和 clipped_image 都返回一个完全白色的 jpg 文件。
有人知道原因是什么吗?
问题似乎是这一行
masked_white_background = cv2.bitwise_and(white_background, white_background, mask=not_mask)
OpenCV docs 说
bitwise_and
返回两个输入数组的并集 where 关键字参数 mask
的计算结果为真。所以你基本上得到的是两个白色背景的按位和。