Python - OpenCV - 裁剪图像并隔离特定对象

时间:2018-01-22 15:02:21

标签: python image opencv

使用python - OpenCV我已成功读取下面的图像,检测矩形,裁剪它们并将每个矩形保存为图像。

Main Image

这是我成功裁剪并保存为图像的矩形样本。 (所以会有12个)

Rectanle Image

然后处理每个矩形图像,以隔离圆圈并为每个圆圈创建一个新图像 - 我已经成功使用cv2.HoughCircles。

图片A的输出包含如下所示的圆圈:

Image contains circle and more

现在:我需要做的是删除绿色圆圈之外的所有内容并将绿色圆圈外的所有内容转换为黑色,然后获取B(仅限绿色圆圈):

Isolated Image Circle

问题是:如何从B获取A

我从OpenCV : Remove background of an image获取代码,但是对于图像A不起作用,例如输出这样的图像:

这是从OpenCV : Remove background of an image获取的代码。

circle_path_test = 'D:\rec.png'

img  = cv2.imread(circle_path_test)
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()       
#rec_img_name_without_extension ,img_ext = os.path.splitext(circle_path_test)                
cv2.imwrite(os.path.join(os.getcwd(), 'dst_circle_gray - Copy.png') , dst) 

1 个答案:

答案 0 :(得分:3)

我回答了类似问题@ OpenCV : Remove background of an image。它对您在问题中发布的图像成功运行。

在下图中失败。因为,代码仅检测到两个圆,或者当内圆是第一个排序的轮廓大于100时。

make it work,您应该make it meet the condition你可以做一些事情来排除非圆形的,非中心的,非常小或太大的。例如:

enter image description here

示例代码:

#!/usr/bin/python3
# 2018.01.20 20:58:12 CST
# 2018.01.20 21:24:29 CST
# 2018.01.22 23:30:22 CST

import cv2
import numpy as np

## (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 first contour that greate than 100, locate in centeral region
## Adjust the parameter when necessary
cnts = cv2.findContours(threshed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2]
cnts = sorted(cnts, key=cv2.contourArea)
H,W = img.shape[:2]
for cnt in cnts:
    x,y,w,h = cv2.boundingRect(cnt)
    if cv2.contourArea(cnt) > 100 and (0.7 < w/h < 1.3) and (W/4 < x + w//2 < W*3/4) and (H/4 < y + h//2 < H*3/4):
        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)

## Display it
cv2.imwrite("dst.png", dst)
cv2.imshow("dst.png", dst)
cv2.waitKey()

结果:

enter image description here