【问题标题】:How to blackout the background of an image after doing contour detection using open in Python?如何在 Python 中使用 open 进行轮廓检测后遮蔽图像的背景?
【发布时间】:2019-04-09 11:44:36
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 Stack Overflow!我们有一个指南如何提出一个好问题。如果您添加更多详细信息(例如您已经在使用的代码),那就太好了,这样会更容易提供帮助,并且您可以期待更快的答案。谢谢!

标签: python opencv opencv-contour


【解决方案1】:

根据您找到的轮廓,使用drawContours 创建一个二进制掩码,在其中填充您的轮廓。取决于您如何执行此操作(黑色图像、白色轮廓与白色图像、黑色轮廓),您将输入图像中的所有像素设置为 0,期望蒙版(或未蒙版)的像素。请参阅以下代码 sn-p 进行可视化:

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)

人工输入图像:

处理过程中生成的掩码:

最终输出:

【讨论】:

    猜你喜欢
    • 2018-09-30
    • 2019-12-06
    • 2019-02-09
    • 2021-04-13
    • 2015-01-11
    • 2016-03-27
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多