如何在Python中使用open进行轮廓检测后遮蔽图像的背景?

问题描述 投票:-2回答:1

我已经使用opencv python检测到图像的轮廓,现在我应该将轮廓外面的图像清空。有人可以帮我这样做吗?

python opencv opencv-contour
1个回答
2
投票

根据您找到的轮廓,使用drawContours创建一个二进制蒙版,在其中填充轮廓。根据您的操作方式(黑色图像,白色轮廓与白色图像,黑色轮廓),您可以将输入图像中的所有像素设置为0,以防止屏蔽(或未屏蔽)。请参阅以下代码片段以获取可视化:

import cv2
import numpy as np

# Artificial input
input = np.uint8(128 * np.ones((200, 100, 3)))
cv2.rectangle(input, (10, 10), (40, 60), (255, 240, 172), cv2.FILLED)
cv2.circle(input, (70, 100), 20, (172, 172, 255), cv2.FILLED)

# Input to grayscale
gray = cv2.cvtColor(input, cv2.COLOR_RGB2GRAY)

# Simple binary threshold
_, gray = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)

# Find contours
cnts, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Generate mask
mask = np.ones(gray.shape)
mask = cv2.drawContours(mask, cnts, -1, 0, cv2.FILLED)

# Generate output
output = input.copy()
output[mask.astype(np.bool), :] = 0

cv2.imwrite("images/input.png", input)
cv2.imwrite("images/mask.png", np.uint8(255 * mask))
cv2.imwrite("images/output.png", output)

人工输入图像:

Input

处理过程中生成的掩码:

Mask

最终输出:

Output

© www.soinside.com 2019 - 2024. All rights reserved.