You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Mask R-CNN提取分割对象并修改图像背景?

解决Mask R-CNN多对象mask背景处理问题

你之前的问题出在每次循环单独用单个mask修改背景,会把之前对象的区域也覆盖成黑色,最后只剩最后一个检测对象。要处理多对象场景,需要把所有检测到的对象mask合并成一个总mask,再用这个总mask统一处理背景。

修改后的代码如下:

import numpy as np
import cv2

# Load Image
img = cv2.imread("/content/image.jpg")

test_model, inference_config = load_inference_model(1, "/content/mask_rcnn.h5")
image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Detect results
r = test_model.detect([image])[0]
colors = random_colors(80)

# 初始化总mask,尺寸和原图一致,初始全为False(背景)
total_mask = np.zeros(img.shape[:2], dtype=bool)

# Get Coordinates and show it on the image
object_count = len(r["class_ids"])
for i in range(object_count):
    # 1. Mask
    mask = r["masks"][:, :, i]
    contours = get_mask_contours(mask)
    for cnt in contours:
        cv2.polylines(img, [cnt], True, colors[i], 2)
        img = draw_mask(img, [cnt], colors[i])
    # 将当前对象的mask合并到总mask中
    total_mask = total_mask | mask

# 处理背景:保留所有对象区域,其余设为黑色
img2 = img.copy()
img2[~total_mask] = [0, 0, 0]

关键说明:

  • total_mask 用逻辑或(|)把每个对象的mask合并,最终所有检测到的对象区域都会被标记为True,背景为False
  • 最后用~total_mask选中所有背景区域,统一设为黑色,这样所有对象都会被保留,不会被之前的循环覆盖

内容的提问来源于stack exchange,提问作者user19153469

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:10:19