python - 在视频中的对象上创建边界框

标签 python opencv find contour box

使用 Python 的 Opencv!
我正在尝试在视频中的对象之间创建边界框。我已经使用了背景减法功能。我正在使用 finContour 函数。现在代码检测视频中“巴士”的边缘并创建一个边界框,但它也检测巴士窗口的边缘并为每个窗口创建一个绑定(bind)框。我只需要在公共(public)汽车上获得一个边界框。

import numpy as np
import cv2
cap = cv2.VideoCapture("C:\\Python27\\clip1.avi")
fgbg = cv2.BackgroundSubtractorMOG()
while(1):
    ret, frame = cap.read()

    fgmask = fgbg.apply(frame)
    # res,thresh = cv2.threshold(fgmask,127,255,0)
    kernel = np.ones((10,10),np.uint8)
    dilation = cv2.dilate(fgmask,kernel,iterations = 1)
    erosion = cv2.erode(fgmask,kernel,iterations = 1)
    contours,hierarchy = cv2.findContours(fgmask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    for i in range(0, len(contours)):
        if (i % 1 == 0):
            cnt = contours[i]


            x,y,w,h = cv2.boundingRect(cnt)
            cv2.drawContours(fgmask ,contours, -1, (255,255,0), 3)
            cv2.rectangle(fgmask,(x,y),(x+w,y+h),(255,0,0),2)



cv2.imshow('frame',fgmask)
cv2.imshow("original",frame)

if cv2.waitKey(30) == ord('a'):
    break

帽释放()
cv2.destroyAllWindows()

enter image description here
enter image description here

最佳答案

import cv2
import numpy as np
#img.png is the fgmask 
img=cv2.imread('img.png')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,th1 = cv2.threshold(gray,25,255,cv2.THRESH_BINARY)
_,contours,hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)


cv2.imshow('image1',img)
cv2.waitKey(0)
cv2.destoryAllWindows(0)

结果

enter image description here

关于python - 在视频中的对象上创建边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35533538/

相关文章:

python - 如何加快 AWS Transcribe 的处理时间?

OpenCV:Flann 匹配器崩溃

python-3.x - 神经网络层的输入形状错误

python - 在 Python find() 调用中使两个字符相等

linux - 在 linux 命令行上反向目录搜索

python - 名称 'BoundMetaData' 未定义

python - 如何将这个多维列表 reshape 为二维数组?

python libcloud 在 vAPP 中创建虚拟机

Python/OpenCV - 间歇性错误

c++ - 在 tr1::shared_ptr 的 vector 中查找元素