【问题标题】:How do I detect only the black rectangle that appears in the reference image with OpenCV如何使用 OpenCV 仅检测参考图像中出现的黑色矩形
【发布时间】:2022-01-07 15:56:24
【问题描述】:

我只需要检测那里出现的黑色矩形,但由于某种原因,我的代码没有检测到它,但它确实检测到了许多其他东西。

import cv2

img=cv2.imread('vision.png') #read image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Blur=cv2.GaussianBlur(gray,(5,5),1) #apply blur to roi
Canny=cv2.Canny(Blur,10,50) #apply canny to roi

#Find my contours
contours =cv2.findContours(Canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)[0]

cntrRect = []
for i in contours:
        epsilon = 0.05*cv2.arcLength(i,True)
        approx = cv2.approxPolyDP(i,epsilon,True)
        if len(approx) == 4:
            cv2.drawContours(img,cntrRect,-1,(0,255,0),2)
            cv2.imshow('Image Rect ONLY',img)
            cntrRect.append(approx)

cv2.waitKey(0)
cv2.destroyAllWindows()

如何只检测图像中出现的黑色矩形

但是这段代码检测到更多的矩形,我不想要 whis,但我只想检测黑色的 countour 矩形

【问题讨论】:

  • 请张贴未经处理的原始图像。
  • @stateMachine 我已经更新了我的问题并合并了原始图像
  • 不要使用 Canny。图像具有高频纹理,Canny 是增强高频分量的高通滤波器。您看到的所有噪音都是高频强度快速改变颜色。正方形似乎有一个漂亮的黑色边框,我的建议是直接对图像进行阈值处理,并尝试用一些形态来隔离正方形的黑色以关闭正方形边缘。然后,可能在图像的四个角进行泛光填充,目标是过滤除实际正方形之外的所有内容。你最终会得到一个白色方块(最大的物体)和一些噪音。
  • @stateMachine 没有 Canny 就更难了
  • 如果您需要大部分直边(以及更简单的东西,如阈值不起作用),请使用 lineSegmentDetector。如果需要任何边缘,可以使用 canny,但在此之前应用适当的低通滤波器

标签: python opencv image-processing


【解决方案1】:

这是在 Python/OpenCV 中执行此操作的一种方法。

阈值图像。然后使用形态学来填充矩形。然后获取最大的轮廓并在输入上绘制。

输入:

import cv2
import numpy as np

# load image
img = cv2.imread("black_rectangle_outline.png")

# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)[1]

# apply close morphology
kernel = np.ones((111,111), np.uint8)
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

# invert so rectangle is white
morph = 255 - morph

# get largest contour and draw on copy of input
result = img.copy()
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
cv2.drawContours(result, [big_contour], 0, (255,255,255), 1)

# write result to disk
cv2.imwrite("black_rectangle_outline_thresh.png", thresh)
cv2.imwrite("black_rectangle_outline_morph.png", morph)
cv2.imwrite("black_rectangle_outline_result.png", result)

# display results
cv2.imshow("THRESH", thresh)
cv2.imshow("MORPH", morph)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

阈值图像:

形态图像:

结果:

【讨论】:

  • 非常好的解决方案!
猜你喜欢
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2017-05-15
  • 1970-01-01
  • 2013-03-23
  • 1970-01-01
相关资源
最近更新 更多