Opencv with Python! I am trying to create bounding boxes across objects in a video. I have already used the background subtraction function. I am using finContour function. Now the code detects the edges of the 'bus' in the video and creates a bounding box, but it also detects the edges of the windows of the bus and creates a bonding box for each of the window. I just need to get a bounding box across the bus only.
用Python打开Opencv!我试图在视频中的对象上创建边界框。我已经使用了背景减法功能。我正在使用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
cap.release() cv2.destroyAllWindows()
1 个解决方案
#1
0
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)
RESULTS
#1
0
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)