gpt4 book ai didi

python - 使用OpenCV识别多个矩形并在其周围绘制边界框

转载 作者:行者123 更新时间:2023-12-02 17:29:26 26 4
gpt4 key购买 nike

我正在尝试在图像中找到的两个矩形周围绘制一个边界框,但不包括弯曲的内衬“噪声”

enter image description here

enter image description here

我尝试了多种方法,包括霍夫线变换(Hough Line Transform)和尝试提取坐标,但无济于事。我的方法似乎太武断了,我试图找到真正的矩形与帧顶部的噪点之间的黑色空间,但无法获得一个合适的常规算法。

最佳答案

这并不是一件容易的事,您可以尝试隔离非常容易区分的垂直线,进行扩张/腐 eclipse 以使矩形成为矩形,然后找到剩下的轮廓并相应地对其进行过滤。看起来像:

import numpy as np
import cv2

minArea = 20 * 20 # area of 20 x 20 pixels

# load image and threshold it
original = cv2.imread("a.png")
img = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
ret, thres = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY )

# Get the vertical lines
verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 10))
vertical = cv2.erode(thres, verticalStructure)
vertical = cv2.dilate(vertical, verticalStructure)

# close holes to make it solid rectangle
kernel = np.ones((45,45),np.uint8)
close = cv2.morphologyEx(vertical, cv2.MORPH_CLOSE, kernel)

# get contours
im2, contours, hierarchy = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# draw the contours with area bigger than a minimum and that is almost rectangular
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
if area > (w*h*.60) and area > minArea:
original = cv2.rectangle(original, (x,y),(x+w,y+h), (0,0,255), 3)

cv2.imshow("image", original)

cv2.waitKey(0)
cv2.destroyAllWindows()

结果是:

enter image description here

enter image description here

如果它不适用于其他图像,请尝试调整参数。

关于python - 使用OpenCV识别多个矩形并在其周围绘制边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56829193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com