trips
trips

Reputation: 1

how can i save the entire frame when the object is detected in a video using python

I want to save the entire frame every time when my model detects the object in the video

import cv2
import time
import numpy as np

# Create our body classifier
car_classifier = cv2.CascadeClassifier('haarcascade_car.xml')

# Initiate video capture for video file
cap = cv2.VideoCapture('K:/b.mp4')

# Loop once video is successfully loaded
while cap.isOpened():
    # Read first frame
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # Pass frame to our car classifier
    cars = car_classifier.detectMultiScale(gray, 1.4, 2)
    print(cars)
    
    # Extract bounding boxes for any bodies identified
    for (x,y,w,h) in cars:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (25, 0, 180), 2)
        cv2.imshow('Cars', frame)

    if cv2.waitKey(1) == 13: #13 is the Enter Key
        break

cap.release()
cv2.destroyAllWindows()

Upvotes: 0

Views: 919

Answers (1)

Alec van der Linden
Alec van der Linden

Reputation: 13

I would simply edit you forloop as such:

foundCarNumber = 0
while cap.isOpened():
    # Read first frame
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # Pass frame to our car classifier
    cars = car_classifier.detectMultiScale(gray, 1.4, 2)
    print(cars)
    # Extract bounding boxes for any bodies identified
    
    foundCar = false;
    for (x,y,w,h) in cars:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (25, 0, 180), 2)
        cv2.imshow('Cars', frame)
        foundCar = true
    
    if(foundCar):
        foundCarNumber += 1
        filePath = "/folder/folder/filename{}.jpg".format(foundCarNumber)
        cv2.imwrite(filePath, frame)

This will generate a filepath + new name everytime you find a car.

The foundCarNumber increment makes sure you do not overwrite your previous image. And the image only gets saved everytime foundCar is true from the forloop.

Upvotes: 1

Related Questions