python运行界面黑色_在Python中使用open执行轮廓检测后,如何使图像的背景变黑?...

1586010002-jmsa.png

I've detected contours for an image using opencv python,now I should blackout the image outside the contour.Could anyone help me to do this?

解决方案

Given your found contours, use drawContours to create a binary mask, in which your contours are filled. Dependent on how you do that (black image, white contours vs. white image, black contours), you set all pixels in your input image to 0 expect for the masked (or unmasked) ones. See the following code snippet for a visualization:

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)

The artificial input image:

zuKp1.png

The mask generated during processing:

JADd1.png

The final output:

t7b7i.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值