Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: take screenshot from video

The idea is that, user should be able to load a video from their local machine and tell the program to take a screenshot from the video every 5sec or 30sec. Is there any library to help me with this task? Any idea from how to proceed would be helpful.

like image 988
asdfkjasdfjk Avatar asked Sep 04 '19 15:09

asdfkjasdfjk


2 Answers

install opencv-python (which is an unofficial pre-built OpenCV package for Python) by issuing the following command:

pip install opencv-python
# Importing all necessary libraries
import cv2
import os
import time

# Read the video from specified path
cam = cv2.VideoCapture("C:/Users/User/Desktop/videoplayback.mp4")

try:

    # creating a folder named data
    if not os.path.exists('data'):
        os.makedirs('data')

    # if not created then raise error
except OSError:
    print('Error: Creating directory of data')

# frame
currentframe = 0

while (True):
    time.sleep(5) # take schreenshot every 5 seconds
    # reading from frame
    ret, frame = cam.read()

    if ret:
        # if video is still left continue creating images
        name = './data/frame' + str(currentframe) + '.jpg'
        print('Creating...' + name)

        # writing the extracted images
        cv2.imwrite(name, frame)

        # increasing counter so that it will
        # show how many frames are created
        currentframe += 1
    else:
        break

# Release all space and windows once done
cam.release()
cv2.destroyAllWindows()
like image 121
ncica Avatar answered Sep 22 '22 14:09

ncica


the above answer is partially right but time.sleep here does not help at all but rather it makes the process slower. however, if you want to take a screenshot at a certain time of a video you need to understand that every time you do "ret, frame = cam.read()" it reads the next frame of the video. every second in a video has a number of frames depends on the video. you get that number using:

  frame_per_second = cam.get(cv2.CAP_PROP_FPS) 

so if you need to take a screenshot of the 3rd second you can keep the iteration as is in the above answer and just add

  if currentframe == (3*frame_per_second):  
      cv2.imwrite(name, frame)

this will take a screenshot of the first frame in the 3rd second.

like image 28
Data_sniffer Avatar answered Sep 22 '22 14:09

Data_sniffer