在给定大小的区域轮廓周围绘制边界框

21 投票
1 回答
82786 浏览
提问于 2025-04-18 04:56

我想在每个封闭的轮廓周围画一个边框,这些轮廓的面积要大于某个阈值,而不仅仅是最大的那个轮廓。我该怎么做呢?

到目前为止,我尝试过这个:

contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    rect = cv2.boundingRect(c)
    if rect[2] < 100 or rect[3] < 100: continue
    print cv2.contourArea(c)
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(im,'Moth Detected',(x+w+10,y+h),0,0.3,(0,255,0))
cv2.imshow("Show",im)
cv2.waitKey()  
cv2.destroyAllWindows()      

1 个回答

29

记住,在Python中,缩进是很重要的。还要注意,你的代码并不是在最大的轮廓周围画框,而是在contours的最后一个元素周围画框。幸运的是,解决这个问题很简单。你只需要调整cv2.rectangle()cv2.putText()的缩进,让它们在每次循环时都能被执行。你还可以通过将rect展开成x,y,w,h来省去一次cv2.boundingRect()的调用。这样你的代码就变成了:

contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    rect = cv2.boundingRect(c)
    if rect[2] < 100 or rect[3] < 100: continue
    print cv2.contourArea(c)
    x,y,w,h = rect
    cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
    cv2.putText(im,'Moth Detected',(x+w+10,y+h),0,0.3,(0,255,0))
cv2.imshow("Show",im)
cv2.waitKey()  
cv2.destroyAllWindows()

撰写回答