如何计算每帧中的边界框?

2024-04-26 07:52:26 发布

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

我需要知道如何计算每帧中的边界框数?在

我需要知道总的边界框,以便知道何时需要添加要跟踪的新对象,total bounding boxes in current frame > total bounding boxes in previous frame

我已经尝试将质心坐标(cx,cy)存储到列表中:

import cv2
import numpy as np

bgsMOG    = cv2.BackgroundSubtractorMOG(50,3,0.8)
cap       = cv2.VideoCapture("d:\\MOV_5702.avi")
a         = []


if cap:
    while True:
        ret, frame = cap.read()
        if ret:
            fgmask              = bgsMOG.apply(frame, None, 0.99)
            contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
            cv2.drawContours(frame,contours,-1,(0,255,0),cv2.cv.CV_FILLED,32)
            try: hierarchy = hierarchy[0]
            except: hierarchy = []
            for contour, hier in zip(contours, hierarchy):
                (x,y,w,h) = cv2.boundingRect(contour)

                if w > 20 and h > 20:
                    cv2.rectangle(frame, (x,y), (x+w,y+h), (180,0,0), 1)
                    (x,y,w,h) = cv2.boundingRect(contour)

                    x1=w/2
                    y1=h/2
                    cx=x+x1
                    cy=y+y1
                    a.append([cx,cy])
                    print(len(a))
                    a=[]

            cv2.imshow('BGS', fgmask)
            cv2.imshow('Ori+Bounding Box',frame)
            key = cv2.waitKey(100)
            if key == ord('q'):
                break
cap.release()
cv2.destroyAllWindows()

但结果总是1。。在

enter image description hereenter image description here


Tags: inifhierarchycv2frametotal边界contour
1条回答
网友
1楼 · 发布于 2024-04-26 07:52:26

在你的代码中,你有

a.append([cx,cy])
print(len(a))
a=[]

因为这是在一个循环中运行的,a在添加了一个项目之后总是会重置为空列表(因此len(a)将始终是1)。在

尝试将a=[]拉到for循环之外,这样它每帧只发生一次,而不是每个轮廓一次,这样可以更好地指示每帧中边界框的数量。在

相关问题 更多 >