无法在OpenCV(Python)中显示轮廓周围的边界矩形

2024-05-29 02:50:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这段代码来画一幅图像中画出的轮廓周围的矩形框,但是在运行中,我得到了所有的东西,除了那些我根本看不见的方框。怎么了?在

for cnt,heir in zip(contours, hierarchy):
    (x,y,w,h) = cv2.boundingRect(cnt);
    cv2.rectangle(im2,(x,y),(x+w,y+h),(0,255,0),2)

cv2.drawContours(im2, contours, -1, (255,255,255), 2);   
cv2.imshow("Contours",im2);

另外,我使用opencv3.1.0和python2.7

编辑:我尝试迭代每个轮廓,为了检查它,我修改了代码如下:

^{pr2}$

我为每个轮廓打印了轮廓区域,每个轮廓的(x,y,w,h)值,在每个轮廓上加上文字“worm”,并在每个轮廓周围画出矩形框。但是我只得到一个输出:

Output for edited code

对于像这样的图像:

Source Image

我需要在每个类似蠕虫的生物上显示“蠕虫”这个文本。但是我只得到一次。问题是什么?在


Tags: 代码in图像forzipcv2轮廓蠕虫
2条回答

只需写下:

for c in contours:
    (x,y,w,h) = cv2.boundingRect(c);
    cv2.putText(im2,'worm',(x+w,y+h), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2, cv2.LINE_AA);
    cv2.rectangle(im2,(x,y),(x+w,y+h),(255,0,0),2);

cv2.drawContours(im2, contours, -1, (255,255,255), 2);   
cv2.imshow("Contours",im2);

正如furas所建议的,如果层次结构只有一对,则zip(轮廓,层次结构)将只返回一对。在这种情况下,轮廓的简单循环列表起作用。在

我曾经用下面的代码在检测到的轮廓上绘制矩形。希望有帮助。在

for contour in contours:
    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # draw rectangle around contour on original image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,255),2)

相关问题 更多 >

    热门问题