在vid中创建跨越对象的边界框

2024-05-21 00:01:57 发布

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

用Python打开cv! 我正在尝试创建一个视频对象的边界框。我已经使用了背景减法功能。我正在使用finContour函数。现在代码检测视频中“总线”的边缘并创建一个边界框,但它也会检测总线窗口的边缘,并为每个窗口创建一个绑定框。我只需要在公共汽车对面放一个接线盒。在

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 hereenter image description here


Tags: import视频ifnpcv2kernelframe边缘
1条回答
网友
1楼 · 发布于 2024-05-21 00:01:57
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

相关问题 更多 >