我需要使用opencv
在下面的图像中找到框。我尝试过使用mser,但我没有得到任何好结果。
我的MSER代码:
mser = cv2.MSER_create()
img = cv2.imread('Lines.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
I = img.copy()
regions, _ = mser.detectRegions(I)
hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]
mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)
c=0
points=[]
for contour in hulls:
[x, y, w, h] = cv2.boundingRect(contour)
if w < 50 or h < 8 or w>120:
continue
c=c+1
cv2.rectangle(I, (x, y), (x + w, y + h), (255, 0, 255), 0)
plt.figure(1,figsize=(100, 50))
plt.imshow(I)
MSER的结果:
由于您的输入图像是反转的,因此请使用“dilate”和合适的结构元素来扩大极值区域,然后应用MSER。
您可以使用opencv提供的cv2.findContours()
函数。您可以使用他们的here教程来了解更多信息。干杯。
您可以对图像进行阈值处理并反转白色和黑色像素,这样您的盒子就会用黑色线条分隔白色:
然后,您可以使用cv2.findContours()
搜索轮廓,然后仅绘制符合您尺寸标准的轮廓。你可以用cv2.contourArea()
获得轮廓的大小。那些轮廓是你的盒子。干杯!
示例代码:
import cv2
img = cv2.imread('table.png')
resize = cv2.resize(img, None, fx=0.3, fy=0.3, interpolation = cv2.INTER_CUBIC)
gray = cv2.cvtColor(resize, cv2.COLOR_BGR2GRAY)
_,thresh = cv2.threshold(gray,50,255,cv2.THRESH_BINARY_INV)
_, contours, _ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
size = cv2.contourArea(cnt)
if 100 < size < 30000:
cv2.drawContours(resize, [cnt], 0, (0,255,0), 1)
cv2.imshow('img', resize)
结果:
我认为你可以使用像素模式来识别盒子。通过示例遍历图像中的每个像素,当您获得白色像素时,然后在x轴和y轴上找到下一个像素颜色。如果两者都是白色,则将该像素视为框的第一个像素。然后取x轴的下一个像素,找到y轴像素。如果它是白色的话你就到达了盒子的另一个角落。如果像素不是白色,则考虑下一个x轴像素。当你在角落时,然后找到下一个y轴像素,直到你到达角落。当你在第三个角落时考虑前一个x像素。然后找到前一个x像素,直到到达第四个角落。然后你可以按四个角的像素坐标保存框。我认为这更准确。但它耗时且复杂。但它可能是新算法。 (仅当盒子是直线时才有效)