Ask Your Question
0

Extract a frame every second in Python

asked 2015-05-16 09:25:37 -0600

Hyperion gravatar image

What I want to do is to put a video as input and extract from it a frame every second keeping the original size and saving all the frames into a folder.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2015-05-17 02:57:25 -0600

harsha gravatar image
import cv2
import math

videoFile = "capture.avi"
imagesFolder = "/other/images"
cap = cv2.VideoCapture(videoFile)
frameRate = cap.get(5) #frame rate
while(cap.isOpened()):
    frameId = cap.get(1) #current frame number
    ret, frame = cap.read()
    if (ret != True):
        break
    if (frameId % math.floor(frameRate) == 0):
        filename = imagesFolder + "/image_" +  str(int(frameId)) + ".jpg"
        cv2.imwrite(filename, frame)
cap.release()
print "Done!"
edit flag offensive delete link more

Comments

Images are not stored in folder specified. And if I remove the path to folder than it save all images in the Presented working directory. Please tell me how to give path to extracted images?

kapil goyal gravatar imagekapil goyal ( 2018-02-03 04:53:54 -0600 )edit

import cv2 import math

videoFile = "video.mp4"

cap = cv2.VideoCapture(videoFile)
frameRate = cap.get(5) #frame rate
x=1
while(cap.isOpened()):
    frameId = cap.get(1) #current frame number
    ret, frame = cap.read()
    if (ret != True):
        break
    if (frameId % math.floor(frameRate) == 0):
        filename = './test_images/image' +  str(int(x)) + ".jpg";x+=1
        cv2.imwrite(filename, frame)

cap.release()
print ("Done!")
Chamod Pathirana gravatar imageChamod Pathirana ( 2018-03-19 07:41:05 -0600 )edit

In line 4, add the whole path with double slash as imagesFolder = "C:\Users\User1\Downloads\Video1"

Iqbal gravatar imageIqbal ( 2018-05-03 01:47:34 -0600 )edit

Hello @harsha@Iqbal, how to do the same extraction for webcam or live video stream ? I want to extract and save frames only one frame after each 2 seconds from webcam stream. Can you advise as simply changing VideoCapture argument to 0 dosen't helps?

trohit gravatar imagetrohit ( 2018-08-14 01:45:31 -0600 )edit

@harsha would u or anyone else please explain how the modulo works? thanks

coderI gravatar imagecoderI ( 2018-11-21 02:44:22 -0600 )edit

@coderI It is saving the last frame every second. If frame rate is 30 fps and x = 30 (it is the 30th frame), it saves the image, one second later after another 30 frames, it will once again save the frame. If it were not conditional, it would try to write as many files per second as the stream's fps which generally would clog the pipeline and hurt throughput.

arya.eshraghi gravatar imagearya.eshraghi ( 2018-11-28 12:37:57 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2015-05-16 09:25:37 -0600

Seen: 39,643 times

Last updated: May 16 '15