Home > Net >  OpenCV finding number of rectangles and writing to video
OpenCV finding number of rectangles and writing to video

Time:06-02

I have a code that detects cars using haar cascade car model, draws rectangles around the detected cars, and generates a video file. I am trying to update the code to show the number of detected cars in each frame.

cap = cv2.VideoCapture(video_src)
car_cascade = cv2.CascadeClassifier(cascade_src)
video = cv2.VideoWriter('result.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, (450,250))  

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)
    cnt=0

    for (x,y,w,h) in cars:
        cv2.rectangle(img,(x,y),(x w,y h),(0,255,255),2)
        cv2.putText(img, str(cnt), (10,200), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 255, 0), 2, cv2.LINE_AA) 
        cnt  = 1
        cv2_imshow(img)

    img=cv2.resize(img,(450,250))
    video.write(img) 

video.release()
cap.release()

When I execute this, some frames have numbers overlaid on each other. I want only one count written on each frame. car count detection

Not sure why this is happening, but I tried to set a delay timer and adjust video write frame speed without luck. I don't know if this method of using cnt to count cars is accurate, but if anyone knows how to fix the number overlay issue or suggest a better way to count total identified cars in each frame that would be great.

CodePudding user response:

I think the problem you have is that for every detected car you call the function cv2.putText(img, str(cnt), (10,200), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 255, 0), 2, cv2.LINE_AA) and it draws a different number for every car. Instead of doing so you should put the line outside the for loop.

cap = cv2.VideoCapture(video_src)
car_cascade = cv2.CascadeClassifier(cascade_src)
video = cv2.VideoWriter('result.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, (450,250))  
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)
        cv2_imshow(img)

    cv2.putText(img, str(len(cars)), (10,200), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 255, 0), 2, cv2.LINE_AA) 

    img=cv2.resize(img,(450,250))
    video.write(img) 
   
video.release()
cap.release()
  • Related