Question

I have obtained the frame_count of a saved video.

self.frame_count = self.capture.get(cv.CV_CAP_PROP_FRAME_COUNT) - 1

Now, I want to start a frame read from a particular frame_count. How do I do this?

Reason: I need to track an object and I have found the location of the object I want to track using HSV image segmentation. Now to track it, I intend to start the video from that particular frame and set the track window to the objects' coordinates.

Want: It should not be redundant and computationally intensive.

Was it helpful?

Solution 2

Try the following:

f = # put here the frame from which you want to start
self.capture.set(CV_CAP_PROP_POS_FRAMES, f)
while f < self.frame_count:
    retval, image = self.capture.read()
    f += 1

OTHER TIPS

Use the below code to accomplish your task.

The Opencv version you are using is old. Use Opencv2.
Link :
http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html

import numpy as np
import cv2
import os

cam = cv2.VideoCapture('full_path/bird.avi')
i = 1 
initialize_first_frame = cam.read()[1]
start_from_frame = 5
dir =  './testImages/'
os.makedirs(dir)
while True:
    if(i>=start_from_frame):
      cv2.imshow('Frame Conversion',cam.read()[1])
      cv2.imwrite(dir + "/image-"+str(i).zfill(5)+".png",cam.read()[1])
    i = i + 1    
    key = cv2.waitKey(10)
    if key == 27:
       cv2.destroyWindow('Frame Conversion')
       break
print "End"

I hope this is the code you want.

For any version 3 and 4 of OpenCV Python, follow this -

import cv2
# suppose you want to start reading from frame no 500
frame_set_no = 500 
cap = cv2.VideoCapture("full_path/cow.mp4")
 
# capture is set to the desired frame
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_set_no)

while True:
  ret, frame = cap.read()
  cv2.imshow("Video", frame)
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cv2.destroyAllWindows()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top