There was a request, so I decided to machine learn about 10 hours of game videos. I made a module to read the video while outputting the progress status to the console.
import cv2
import sys
fpath = 'data/videos/sample_video.mp4'
video = cv2.VideoCapture(fpath)
can_read, first = video.read()
if not can_read:
sys.exit()
progress_step = 60 #Show progress once every 60 frames
count = 0
max = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
while video.isOpened():
if(count % progress_step == 0):
print(f'Progress rate: {count}/{max}')
ok, frame = video.read()
if ok:
#What you want to do
else:
break
video.release()
Progress rate: 0/2700
Progress rate: 60/2700
Progress rate: 120/2700
Progress rate: 180/2700
...
Although the purpose has been achieved, other programs also have video loading processing, and I want to reuse it there, so I decided to make it a function that can be called from anywhere.
reader.py
def video_read(input):
"""
Parameters
----------
input: str
Input video path
Returns
------
Iterator[np.ndarray]
Generator of video frame
"""
# video capture start
video = cv2.VideoCapture(input)
can_read, first = video.read()
if not can_read:
print('Cannot read video file')
return
max = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
yield first
progress_step = 60 #Show progress once every 60 frames
count = 0
while video.isOpened():
if(count % progress_step == 0):
print(f'Progress rate: {count}/{max}')
ok, frame = video.read()
if ok:
count += 1
yield frame
else:
break
video.release()
import reader
it = reader.video_read('data/videos/sample_video.mp4')
try:
first = next(it)
except StopIteration:
sys.exit()
for image in it:
#What you want to do
The caller was very refreshing. I think that the video loading process and the main process you want to do have been separated and clarified. I feel like I made good use of the Python generator. I'm sorry for this article, regardless of the smasher ...
Recommended Posts