OpenCV:删除图像的背景 [英] OpenCV : Remove background of an image

查看:2983
本文介绍了OpenCV:删除图像的背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Opencv和python来检测形状然后裁剪它们。我已经成功了,但是现在我正在尝试拍摄裁剪的图像并删除它们的背景。

I am using Opencv and python to detect shapes and then crop them. I have succeeded to do that, however now I am trying to take the cropped images and remove their backgrounds.

图像内部有一个圆圈,周围是灰色。 ( 它可以是灰色的,也可以是多种颜色 )。

The image has a circle inside and surrounded by gray color. (It can be gray or can be even more than one color).

如何删除圆圈边界周围的颜色(这是黑色) - 我们可以将灰色转换为黑色 - 作为边框颜色,甚至可以将其删除并使其透明。

How can I remove the colors surrounding the circle border (which is black) - we can convert the gray color to black - as the border color or even remove it at all and make that transparent.

结果图片应仅包含圆圈。

The result image should contain only the circle.

推荐答案

至少对于此图片,没有需要检测圆圈使用 houghCircle)。我认为阈值它和找到内部轮廓,然后 make mask 执行bitwise-op 即可!

At least in for this image, there is no need to detect the circle use houghCircle). I think threshold it and find the inner contour , then make mask and do bitwise-op is OK!

我的步骤:


(1)阅读并转换为灰色

(1) Read and convert to gray

(2)findContours

(2) findContours

(3)find轮廓较小,创建一个面具

(3) find contour that smaller, create a mask

(4)执行 bitwise_and 裁剪






这是我的结果:


Here is my result:

#!/usr/bin/python3
# 2018.01.20 20:58:12 CST
# 2018.01.20 21:24:29 CST
import cv2
import numpy

## (1) Read
img = cv2.imread("img04.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

## (2) Threshold
th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)

## (3) Find the min-area contour
_, cnts, _ = cv2.findContours(threshed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key=cv2.contourArea)
for cnt in cnts:
    if cv2.contourArea(cnt) > 100:
        break

## (4) Create mask and do bitwise-op
mask = np.zeros(img.shape[:2],np.uint8)
cv2.drawContours(mask, [cnt],-1, 255, -1)
dst = cv2.bitwise_and(img, img, mask=mask)

## Save it
cv2.imshow("dst.png", dst);cv2.waitKey()

这篇关于OpenCV:删除图像的背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆