我有一个 30 fps 的视频。 我需要以 1 FPS 的速度从视频中提取帧。这在 Python 中如何实现?
我有以下从网上获得的代码,但我不确定它是否以 1 FPS 提取帧。 请帮忙!
# Importing all necessary libraries
import cv2
import os
# Read the video from specified path
cam = cv2.VideoCapture("C:\\Users\\Admin\\PycharmProjects\\project_1\\openCV.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):
# 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()
KPS = 1# Target Keyframes Per Second
VIDEO_PATH = "video1.avi"#"path/to/video/folder" # Change this
IMAGE_PATH = "images/"#"path/to/image/folder" # ...and this
EXTENSION = ".png"
cap = cv2.VideoCapture(VIDEO_PATH)
fps = round(cap.get(cv2.CAP_PROP_FPS))
print(fps)
# exit()
hop = round(fps / KPS)
curr_frame = 0
while(True):
ret, frame = cap.read()
ifnot ret: break
if curr_frame % hop == 0:
name = IMAGE_PATH + "_" + str(curr_frame) + EXTENSION
cv2.imwrite(name, frame)
curr_frame += 1
cap.release()
这是我需要从视频中提取帧时使用的代码:
# pip install opencv-python
import cv2
import numpy as np
# video.mp4 is a video of 9 seconds
filename = "video.mp4"
cap = cv2.VideoCapture(filename)
cap.set(cv2.CAP_PROP_POS_AVI_RATIO,0)
frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
frameWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frameHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
videoFPS = int(cap.get(cv2.CAP_PROP_FPS))
print (f"frameCount: {frameCount}")
print (f"frameWidth: {frameWidth}")
print (f"frameHeight: {frameHeight}")
print (f"videoFPS: {videoFPS}")
buf = np.empty((
frameCount,
frameHeight,
frameWidth,
3), np.dtype('uint8'))
fc = 0
ret = True
while (fc < frameCount):
ret, buf[fc] = cap.read()
fc += 1
cap.release()
videoArray = buf
print (f"DURATION: {frameCount/videoFPS}")
您可以了解如何提取视频的特征,例如
frameCount
、frameWidth
、frameHeight
、videoFPS
最后,持续时间应为帧数除以
videoFPS
变量。
所有帧都存储在
buf
内,因此如果您只想提取 1 帧,请迭代 buf 并仅提取 9 帧(每次迭代都会增加视频 FPS)。
这是我发现效果最好的代码。
import os
import cv2
import moviepy.editor
def getFrames(vid, output, rate=0.5, frameName='frame'):
vidcap = cv2.VideoCapture(vid)
clip = moviepy.editor.VideoFileClip(vid)
seconds = clip.duration
print('duration: ' + str(seconds))
count = 0
frame = 0
if not os.path.isdir(output):
os.mkdir(output)
success = True
while success:
vidcap.set(cv2.CAP_PROP_POS_MSEC,frame*1000)
success,image = vidcap.read()
## Stop when last frame is identified
print(frame)
if frame > seconds or not success:
break
print('extracting frame ' + frameName + '-%d.png' % count)
name = output + '/' + frameName + '-%d.png' % count # save frame as PNG file
cv2.imwrite(name, image)
frame += rate
count += 1
rate
参数的值为1/fps