Reputation: 177
I am trying to capture every 200th frame from each video in a directory. I wrote a code to solve that, but the problem is it extracts all the frames from one video and then move to the next video. But I am trying to extract frame from one video and then the same frame from the next video and so on and once that n-th frame is extracted from all the videos then increase the frame counter and start extracting the next frame in the same order.
My code snippet is as follow:
for samples in path: # path is a list of all the video samples
video = os.path.join(rootDir, samples)
cap = cv2.VideoCapture(video)
frameRate = 200 # frame rate
currentframe=1
while(cap.isOpened()):
frameId = cap.get(1)
ret, frame = cap.read() # reading from frame
if (ret != True):
break
currentframe+=1
if (currentframe % math.floor(frameRate) == 0):
filename = './'+str(samples[:-4])+'/image'+str(int(currentframe))+".jpg"
print('Creating...'+filename)
cv2.imwrite(filename, frame)
# Release all the sape and windows once done
cap.release()
Upvotes: 2
Views: 310
Reputation: 369
A solution could be something like this, creating a list of cap objects called caps and iterate over it.
caps = []
for samples in path: # path is a list of all the video samples
video = os.path.join(rootDir, samples)
cap = cv2.VideoCapture(video)
caps.append(cap)
frameRate = 200 # frame rate
currentframe=1
while(caps[0].isOpened()):
frames = []
for cap in caps:
ret, frame = cap.read() # reading from frame
frames.append(frame)
if (ret != True):
break
currentframe+=1
if (currentframe % math.floor(frameRate) == 0):
for frame in frames:
#filename = './'+str(samples[:-4])+'/image'+str(int(currentframe))+".jpg"
#print('Creating...'+filename)
#cv2.imwrite(filename, frame)
# Release all the sape and windows once done
for cap in caps:
cap.release()
Upvotes: 1