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

这是我成功裁剪并另存为图像的矩形的示例。(因此将有12个)

然后处理每个矩形图像,以隔离圆并为每个圆创建一个新图像-使用cv2.HoughCircles我也成功做到了。
图像的输出A包含圆圈,如下所示:

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

现在的问题是:如何获得B从A。
我从OpenCV中获取代码:删除图像的背景,但不适用于该图像A,而是输出此类图像:

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)
Run Code Online (Sandbox Code Playgroud)
我回答了类似的问题@ OpenCV:删除图像的背景。对于您在问题中发布的图像,它可以成功运行。
下图失败。因为,该代码仅用于检测到两个圆,或者当内部圆是第一个大于的轮廓时100。

要make it work,你应该make it meet the condition。您可以采取一些措施来排除非圆形,非中心,太小或太大的圆形。如:
示例代码:
#!/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()
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
6817 次 |
| 最近记录: |