Python OpenCV 检测轮廓形状顶点的宽度和高度

时间:2021-03-19 08:22:45

标签: python opencv

我们使用 Python OpenCV 来检测形状。我在这里使用代码来检测形状。 https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/

如何找到下方矩形的宽高?通过查看下面的所有顶点组合,我可以找到 x 值之间的最大减法差异和 y 值的最大差异。好奇 Python OpenCV 库是否有更有效的方法来执行此操作。 如果处理五边形或六边形,或者具有许多顶点轮廓的形状,该算法可能会更麻烦。

cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

for contourItem in cnts:

    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)

    if len(approx) == 3:
        shape = "triangle"

    elif len(approx) == 4:
        (x, y, w, h) = cv2.boundingRect(approx)
        ar = w / float(h)
        shape = "square" if ar >= 0.95 and ar <= 1.05 else "rectangle"

    elif len(approx) == 5:
        shape = "pentagon"

顶点结果:

1 = 
 xLocation = 341
 yLocation = 372
2 = 
 xLocation = 277
 yLocation = 410
3 = 
 xLocation = 348
 yLocation = 529
4 = {
 xLocation = 412
 yLocation = 493

Shape Values

资源:How to detect simple geometric shapes using OpenCV

1 个答案:

答案 0 :(得分:0)

使用 x,y,w,h = cv.boundingRect() 作为上述注释,或者也可以使用 cv2.minAreaRect()

<块引用>

7.a. Straight Bounding Rectangle 是一个直线矩形,不考虑物体的旋转。所以边界的面积 矩形不会是最小的。它是通过函数找到的 cv2.boundingRect().

设 (x,y) 是矩形的左上角坐标,(w,h) 是它的 宽度和高度。

x,y,w,h = cv2.boundingRect(cnt) 
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
<块引用>

7.b. Rotated Rectangle 这里,边界矩形是用最小面积绘制的,所以它也考虑了旋转。使用的函数是 cv2.minAreaRect()。它返回一个 Box2D 结构,其中包含 以下细节 - (左上角(x,y),(宽度,高度),角度 回转 )。但是要绘制这个矩形,我们需要矩形的 4 个角 矩形。它由函数 cv2.boxPoints()

获得
rect = cv2.minAreaRect(cnt) 
box = cv2.boxPoints(rect) 
box = np.int0(box)
im = cv2.drawContours(im,[box],0,(0,0,255),2)

Rectangle Image Picture

也感谢 DragonsCanDance 用户

来自资源:Python resource