【问题标题】:Python - OpenCV - Cropping images and isolating specific objectsPython - OpenCV - 裁剪图像并隔离特定对象
【发布时间】:2018-07-01 06:10:39
【问题描述】:

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

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

然后处理每个矩形图像,以便隔离圆并为每个圆创建一个新图像 - 我也使用 cv2.HoughCircles 成功地做到了。

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

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

问题是:如何从A 得到B

我从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) 

【问题讨论】:

  • 明确一点:除了中心还有其他圆圈吗?其他区域会是绿色还是与中心圆相似?
  • 除了中间的那个圆圈外,没有其他圆圈。是的。圆圈外的其他一些区域可以是绿色或类似于圆圈内的颜色。
  • 好的,我会更新的。

标签: python image opencv


【解决方案1】:

我回答了类似的问题@OpenCV : Remove background of an image。它适用于您在问题中发布的图像。


在下图中失败了。因为,代码只针对检测到的两个圆,或者当内圆是大于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()

结果:

【讨论】:

  • 非常感谢。你是最棒的 。它工作得很好:-)再次感谢您。
  • 让我看看我怎么能接受这个答案。我是这个网站的新手......希望我有这样的声誉
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
  • 2017-08-04
  • 2018-09-09
  • 2021-05-05
  • 2012-10-17
相关资源
最近更新 更多