繁体   English   中英

如何使用 OpenCV 仅检测参考图像中出现的黑色矩形

[英]How do I detect only the black rectangle that appears in the reference image with OpenCV

我只需要检测出现在那里的矩形,但由于某种原因它没有检测到它,但它确实检测到了许多其他小人仔

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 矩形在此处输入图像描述

原始图像

在此处输入图像描述

这是在 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()

阈值图像:

在此处输入图像描述

形态图像:

在此处输入图像描述

结果:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM