Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Created May 10, 2017 19:30
Show Gist options
  • Save keithweaver/70df4922fec74ea87405b83840b45d57 to your computer and use it in GitHub Desktop.
Save keithweaver/70df4922fec74ea87405b83840b45d57 to your computer and use it in GitHub Desktop.
Using OpenCV takes a mp4 video and produces a number of images.
'''
Using OpenCV takes a mp4 video and produces a number of images.
Requirements
----
You require OpenCV 3.2 to be installed.
Run
----
Open the main.py and edit the path to the video. Then run:
$ python main.py
Which will produce a folder called data with the images. There will be 2000+ images for example.mp4.
'''
import cv2
import numpy as np
import os
# Playing video from file:
cap = cv2.VideoCapture('example.mp4')
try:
if not os.path.exists('data'):
os.makedirs('data')
except OSError:
print ('Error: Creating directory of data')
currentFrame = 0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Saves image of the current frame in jpg file
name = './data/frame' + str(currentFrame) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
# To stop duplicate images
currentFrame += 1
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
@rsomani95
Copy link

@Arnold1

Adding if not ret: break in the loop did the trick to me.


On the other hand,

cap.set(cv2.CAP_PROP_FPS, FPS)

returns False for any value of FPS (I tried both an int and a float -- does it accept both?). What does this mean? Can I ignore this/ omit this piece of code entirely?

@Djotchuang
Copy link

Djotchuang commented Jun 26, 2019

I added if not ret: break in the loop and it worked for me. That is, the number of frames were fewer.

@rekhasharma-kmm
Copy link

when i run this code ,my console gives this message.
warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)
warning: C:\PythonProgram�ideo.mp4 (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)
Traceback (most recent call last):
File "GettingFrame.py", line 16, in
name='.data/frame'+str(currentFrame)+'.jpg'
NameError: name 'currentFrame' is not defined
Please rectify it.

@sajidAli110
Copy link

i want to take video of class room student when i upload video program will automatically convert video into images and match if both mach student will be tarted as present.

@DuslerOtesi
Copy link

nothing data is there inside the data folder.

@roczy
Copy link

roczy commented Apr 4, 2020

How would one snapshot photos from the video frames so that these snapshots are save every minute up until 24 hours?

@anuja1005
Copy link

I am trying same code in Pycharm-django project but I am getting following stream of errors. I am new at it so I don't know how to fix this.

Errors :
Traceback (most recent call last):
File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy_init_.py", line 142, in
from . import core
File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core_init_.py", line 24, in
from . import multiarray
File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core\multiarray.py", line 14, in
from . import overrides
File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\numpy\core\overrides.py", line 16, in
add_docstring(
RuntimeError: implement_array_function method already has a docstring
Traceback (most recent call last):
File "C:/Users/Dell/Desktop/pp/test2/templates/ex.py", line 1, in
import cv2
File "C:\Users\Dell\Desktop\pp\test2\venv\lib\site-packages\cv2_init_.py", line 5, in
from .cv2 import *
ImportError: numpy.core.multiarray failed to import

Does anyone know how to fix this ?

@sujithgunturu
Copy link

I need break the movie at 15 frames per second. I tried the following code but it does not work. Instead it is breaking with 25 frames per second

FramesPerSecond = 15
captureTheVideo = cv2.VideoCapture('a.mp4')
captureTheVideo.set(cv2.CV_CAP_PROP_FPS, FramesPerSecond)

@927drish
Copy link

what algorithm to use to select best frame?

@aiwithshekhar
Copy link

nice, not working

@oofmaloo
Copy link

oofmaloo commented May 21, 2023

In case anyone wants to skip frames / and use youtube clips

import cv2
import numpy as np
import os
from cap_from_youtube import cap_from_youtube

# Playing video from file:
youtube_url = 'https://www.youtube.com/watch?v=6j1Oj5N7kwE'
cap = cap_from_youtube(youtube_url, 'best')

try:
    if not os.path.exists('data'):
        os.makedirs('data')
except OSError:
    print ('Error: Creating directory of data')

fps = 25
seconds_to_skip = 30
# fps * seconds_to_skip

# start frame is
currentFrame = 8500
# if you want a start frame use this, otherwise set currentFrame to 0 and comment line below
cap.set(cv2.CAP_PROP_POS_FRAMES, currentFrame)
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    if ret:
        print ('Creating frame...' + str(currentFrame))
        cv2.imwrite('./data/frame{:d}.jpg'.format(currentFrame), frame)
        currentFrame += (fps * seconds_to_skip) # i.e. at 30 fps, this advances one second
        cap.set(cv2.CAP_PROP_POS_FRAMES, currentFrame)
    else:
        cap.release()
        break

# When everything done, release the capture
cv2.destroyAllWindows()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment