Python 如何让所有轮廓的外侧变黑?

Python how to make the outside of all contours black?

我正在使用 mask-RCNN 检测图像中的对象,然后我使用像这样的对象蒙版在图像上绘制轮廓 contours in an image

然后我想让这些轮廓外的每个像素都变成黑色,如下所示:contours with black background 那么有没有简单的方法呢?

在绘制轮廓时使用 cv2.FILLED 获取蒙版并将其应用于原始图像。 例如:

black_canvas = np.zeros_like(img_gray)
cv2.drawContours(black_canvas, contours, -1, 255, cv2.FILLED) # this gives a binary mask 

假设您有轮廓,您可以通过首先创建轮廓的蒙版图像然后使用该蒙版执行 bitwise_and 操作来获得结果。

maskImage = np.zeros(img.shape, dtype=np.uint8)
cv2.drawContours(maskImage, Contours, -1, (255, 255, 255), -1)

newImage = cv2.bitwise_and(img, maskImage)