I am trying to use use this code (https://github.com/Aman-Preet-Singh-Gulati/Vehicle-count-detect) to detect the number of vehicles and write a video file with bounding boxes. I have successfully used this code on the image file, but the code is not generating a video file for some reason.
I am using haar cascade car model (verified the .xml file works on a picture) and writing a video file using the following code:
cascade_src = 'cars.xml'
video_src = 'Cars.mp4'
cap = cv2.VideoCapture(video_src)
car_cascade = cv2.CascadeClassifier(cascade_src)
video = cv2.VideoWriter('result.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, (450,250))
The resulting file is a few kilobytes and cannot be played. I am trying to get some help to figure out how to make this step work.
Assuming this step works, the next block of code is supposed to generate bounding boxes and write to a file. Will this create a new file or overwrite the previously generated video file with the bounding boxes?
while True:
ret, img = cap.read()
if (type(img) == type(None)):
break
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectMultiScale(gray, 1.1, 2)
for (x,y,w,h) in cars:
cv2.rectangle(img,(x,y),(x w,y h),(0,255,255),2)
video.write(img)
video.release()
Thanks a lot! I am a total beginner in Python so appreciate the help.
CodePudding user response:
I see two possible problems:
you have
write()
in wrong place. It has to be insidefor
-loop. You write only last image.if original file has size different than
(450,250)
then you have to resize image before writing. It will NOT resize it automatically but it will skip image if it has wrong size. And finally it will create file without images/frames - so it will create broken file.
import cv2
cascade_src = 'cars.xml'
video_src = 'Cars.mp4'
cap = cv2.VideoCapture(video_src)
car_cascade = cv2.CascadeClassifier(cascade_src)
video = cv2.VideoWriter('result.avi', cv2.VideoWriter_fourcc(*'DIVX'), 15, (450, 250))
# --- loop ---
while True:
ret, img = cap.read()
if ret is False:
break
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectMultiScale(gray, 1.1, 2)
for x, y, w, h in cars:
cv2.rectangle(img, (x,y), (x w, y h), (0, 255, 255), 2)
img = cv2.resize(img, (450, 250))
video.write(img)
# --- after loop ---
video.release()
cap.release()