Python: take screenshot from video - python

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.

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()

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.

#ncica & Data_sniffer solution remake
import cv2
import os
import time
step = 10
frames_count = 3
cam = cv2.VideoCapture('video/example.MP4')
currentframe = 0
frame_per_second = cam.get(cv2.CAP_PROP_FPS)
frames_captured = 0
while (True):
ret, frame = cam.read()
if ret:
if currentframe > (step*frame_per_second):
currentframe = 0
name = 'photo/frame' + str(frames_captured) + '.jpg'
print(name)
cv2.imwrite(name, frame)
frames_captured+=1
if frames_captured>frames_count-1:
ret = False
currentframe += 1
if ret==False:
break
cam.release()
cv2.destroyAllWindows()

#a generic function incorporating all the comments mentioned above.
def get_frames(inputFile,outputFolder,step,count):
'''
Input:
inputFile - name of the input file with directoy
outputFolder - name and path of the folder to save the results
step - time lapse between each step (in seconds)
count - number of screenshots
Output:
'count' number of screenshots that are 'step' seconds apart created from video 'inputFile' and stored in folder 'outputFolder'
Function Call:
get_frames("test.mp4", 'data', 10, 10)
'''
#initializing local variables
step = step
frames_count = count
currentframe = 0
frames_captured = 0
#creating a folder
try:
# creating a folder named data
if not os.path.exists(outputFolder):
os.makedirs(outputFolder)
#if not created then raise error
except OSError:
print ('Error! Could not create a directory')
#reading the video from specified path
cam = cv2.VideoCapture(inputFile)
#reading the number of frames at that particular second
frame_per_second = cam.get(cv2.CAP_PROP_FPS)
while (True):
ret, frame = cam.read()
if ret:
if currentframe > (step*frame_per_second):
currentframe = 0
#saving the frames (screenshots)
name = './data/frame' + str(frames_captured) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
frames_captured+=1
#breaking the loop when count achieved
if frames_captured > frames_count-1:
ret = False
currentframe += 1
if ret == False:
break
#Releasing all space and windows once done
cam.release()
cv2.destroyAllWindows()

To add on data_sniffer's answer. I would recommend using round (Math function) on frame_per_second when checking as if the frame rate is a decimal number then it will go into an infinite loop.

The solutions provided do not work for me in several cases.
The FPS from cv2.CAP_PROP_FPS is a floating point value and the FPS rate of my testvid.mp4 was 23.976023976023978 according to this property.
When looping through current_frame / fps % 3, we will almost always have leftovers because of this floating point value. Same goes for (3*frame_per_second):, causing our imwrite to never be reached.
I solved this issue by using the same calculations, but storing the remainders and comparing those:
current_frame = 0
fps_calculator_previous = 0
while (True):
ret, frame = cam.read()
if ret:
# Still got video left.
file_name = f"./data_generation/out/{_fn}-{current_frame}.jpg"
fps_calculator = (current_frame / fps) % every_x_sec
if(fps_calculator - fps_calculator_previous < 0):
print("Found a frame to write!")
cv2.imwrite(file_name, frame)
fps_calculator_previous = fps_calculator
current_frame += 1
else:
break
This seems to work well for me with any value for both cv2.CAP_PROP_FPS as well as every_x_sec
My video was 18 minutes and 7 seconds long, and I captured 362 unique frames from that with every_x_sec set to 3.

Edited #ncica's code and noted that it is working fine.
import cv2
import os
import time
cam = cv2.VideoCapture("/path/to/videoIn.mp4")
try:
if not os.path.exists('data'):
os.makedirs('data')
except OSError:
print('Error: Creating directory of data')
intvl = 2 #interval in second(s)
fps= int(cam.get(cv2.CAP_PROP_FPS))
print("fps : " ,fps)
currentframe = 0
while (True):
ret, frame = cam.read()
if ret:
if(currentframe % (fps*intvl) == 0):
name = './data/frame' + str(currentframe) + '.jpg'
print('Creating...' + name)
cv2.imwrite(name, frame)
currentframe += 1
else:
break
cam.release()
cv2.destroyAllWindows()
The trick is it is looping frame-by-frame.
So, here we are capturing frames that we want and write disk as snapshot image file.
eg : If you want snapshot two second by two second intvl must be 2

Related

Problem with naming a camera captured file in a while-loop

This is my code, It takes a picture via webcam and saves it in a folder I specify. The name is then "day-time_0/1/2/3.jpg".
The problem is I would like to have it without "_0/1/2/3". But these numbers are necessary for the loop I think at least. But if I take out this count it saves a picture and over saves it every time I want to make another picture in the same interface.
Is there a way that if I am in the same interface and take several pictures that I can save them again and again with the new current time?
import cv2
import os
import time
timestr = time.strftime("%Y%m%d-%H%M%S")
def save_frame_camera_key(device_num, dir_path, basename, ext='jpg', delay=1, window_name='frame'):
cap = cv2.VideoCapture(device_num)
if not cap.isOpened():
return
os.makedirs(dir_path, exist_ok=True)
base_path = os.path.join(dir_path, basename)
n = 0
while True:
ret, frame = cap.read()
cv2.imshow(window_name, frame)
key = cv2.waitKey(delay) & 0xFF
if key == ord('c'):
cv2.imwrite('{}_{}.{}'.format(base_path, **n**, ext), frame)
** n += 1**
elif key == ord('q'):
break
cv2.destroyWindow(window_name)
save_frame_camera_key(0, 'data/temp', timestr)
As i said i tried deleting the count. Didnt work. Ive tried it with an different capture Code and it didnt work.

Read and extract keypoints from folder of videos opencv

I have a list of videos (10 sec each) in a folder and I'm trying to loop through each action video to extract keypoints and save them as json files.
path = "path to video folder"
for file in os.listdir(path):
cap = cv2.VideoCapture(path+file)
while cap.isOpened():
try:
ret, frame = cap.read()
I ran into a problem where the extracted data has some keypoints from other videos, and I just want to run this code, end with the stop time for the video is done, pause, start next video. How can I help correct this?
If you want to process multiple videos in turn you can check the ret (success) value of cap.read() to detect the end of each file. Here is a basic example you can start with:
import os
import cv2
path = "videos"
for file in os.listdir(path):
print(file)
cap = cv2.VideoCapture(path + '/' + file)
count = 0
while True:
ret, frame = cap.read()
# check for end of file
if not ret:
break
# process frame
count += 1
print(f"{count} frames read")
cap.release()

I have a problem to extract images from video and save them to specific folder

everyone.
I'm a struggling freshman for programming.
I'll really appreciate any of your help or advice.
I want to make this code do these jobs.
Read video files in specific folder.
Extract frame image from this video file
Save them in specific folder(ex. from video_1.mp4, make folder video_1_frameimage and save images video_1_frame0, video_1_frame300, ..... and so on into this specific folder)
To make this function I made this code but it doesn't work that nicely.
Thank you for reading my question!
import cv2
import os
path_for_video = "C:/Users/정지원/Desktop/Video_files"
video_list = os.listdir(path_for_video)
for video_file in video_list:
file_path= os.path.join(path_for_video,video_file)
cap = cv2.VideoCapture(file_path)
index = 0
while (True):
ret, frame = cap.read()
if ret == False:
break
if index % 300 == 0:
name = video_file + '_frame' + str(index) + '.jpg'
print('Creating...' + name)
if not os.path.exists('C:/Users/정지원/Desktop/Video_files/'+ video_file):
os.makedirs('C:/Users/정지원/Desktop/Video_files/' + video_file)
path_for_image = 'C:/Users/정지원/Desktop/Video_files/' + video_file
cv2.imwrite(os.path.join(path_for_image, name), frame)
index += 1
cap.release()
cv2.destroyAllWindows()

Why does my code using OpenCv extracts less number of frame from a video

When I used below built-in properties of OpenCv to count number of frame of a video, its shows correct result.
video = cv2.VideoCapture(path)
total = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
But, when I tried to save all those frames, its store less number of frames. Below is another code for saving frame-
def ExtractFrames(self, videoPath):
srcVideo = cv2.VideoCapture(videoPath)
try:
if not os.path.exists('VideoFrames'):
os.makedirs('VideoFrames')
except OSError:
print('Error: Creating directory.')
currentframe = 0
while (True):
success, image = srcVideo.read()
if success:
fileName = './VideoFrames/frame' + str(currentframe) + '.jpg'
self.lstVideoFrames.append(fileName)
cv2.imwrite(fileName, image)
currentframe += 1
else:
break

How to print 1 in every thousand frames using opencv and python?

I am trying to save one frame in every thousand frames of a video. Below is the code I am currently using:
import cv2
import numpy as np
import os
# Playing video from file:
cap = cv2.VideoCapture('D:/01 Projects/AMAZON CATALYST PROJECT/Surgery1.mpg')
try:
if not os.path.exists('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1'):
os.makedirs('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1')
except OSError:
print ('Error: Creating directory of data_surg1')
currentFrame = 0
while(True):
# Capture frame-by-frame
if currentFrame > 0:
cap.set(cv2.CAP_PROP_POS_MSEC,currentFrame)
ret, frame = cap.read()
# Saves image of the current frame in jpg file
name = 'D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1/frame' + str(currentFrame/1000) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
# To stop duplicate images
currentFrame += 1000
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
However, I am not sure if this is saving it correctly. When I look at the frames in the file explorer, the numbers are initially very high and then reduce to form a sequential frame number compared to the previous image. I am using Python 2.7 and OpenCV3.3.
For storing from certain frames instead of a time-based save, the following script works:
import cv2
import numpy as np
import os
# Playing video from file:
cap = cv2.VideoCapture('D:/01 Projects/AMAZON CATALYST PROJECT/Surgery1.mpg')
try:
if not os.path.exists('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1'):
os.makedirs('D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1')
except OSError:
print ('Error: Creating directory of data_surg1')
currentFrame = 0
while(True):
# Capture frame-by-frame
if currentFrame > 0:
cap.set(cv2.CAP_PROP_POS_FRAMES,currentFrame)
ret, frame = cap.read()
# Saves image of the current frame in jpg file
name = 'D:/01 Projects/AMAZON CATALYST PROJECT/data_surg1/frame' + str(currentFrame/1000) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
# To stop duplicate images
currentFrame += 1
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Categories