使用Python将视频转换为帧-1 FPS

问题描述

我有一个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()

解决方法

这是我需要从视频中提取帧时使用的代码:


# 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}")

您可以看到如何提取视频的特征,例如frameCountframeWidthframeHeightvideoFPS

最后,持续时间应为帧数除以videoFPS变量。

所有帧都存储在buf内,因此,如果要仅提取1个帧,则对buf进行迭代,并且只提取9个帧(每次迭代增加视频FPS)。

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...