import numpy as np
import cv2 as cv
cap = cv.VideoCapture("walking")
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(3,3))
fgbg = cv.bgsegm.createBackgroundSubtractorGMG()
while(1):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
fgmask = cv.morphologyEx(fgmask, cv.MORPH_OPEN, kernel)
im2, contours, hierarchy = cv.findContours(fgmask, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(fgmask, contours, -1, (0,255,0), 3)
if len(contours) > 0:
for count in contours:
x,y,w,h = cv.boundingRect(count)
cv.rectangle(fgmask,(x,y),(x+w,y+h),(0,255,0),2)
cv.imshow('frame',fgmask)
cv.imshow("stan",frame)
k = cv.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv.destroyAllWindows()
这是我的代码,我试图在视频中围绕轮廓设置一个方框,在这种情况下是多个行人走路。根本没有盒子出现,我在某个地方犯了一个简单的错误吗?
答案 0 :(得分:0)
缩进错误。检测到的轮廓的边界框的绘制以及显示结果不在while
循环中。因此,您只是在阅读框架,查找这些框架的轮廓,但您没有在显示窗口上显示它们。
当您在视频中阅读时,您需要对框架进行更新。
取while
循环和后面的前5行并将其移至缩进级别0:
import numpy as np
import cv2 as cv
cap = cv.VideoCapture("walking")
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(3,3))
fgbg = cv.bgsegm.createBackgroundSubtractorGMG()
while(1):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
fgmask = cv.morphologyEx(fgmask, cv.MORPH_OPEN, kernel)
im2, contours, hierarchy = cv.findContours(fgmask, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(fgmask, contours, -1, (0,255,0),
if len(contours) > 0:
for count in contours:
x,y,w,h = cv.boundingRect(count)
cv.rectangle(fgmask,(x,y),(x+w,y+h),(0,255,0),2)
cv.imshow('frame',fgmask)
cv.imshow("stan",frame)
k = cv.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv.destroyAllWindows()