首页 > 解决方案 > 在 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()

标签: pythonvideo-capturecv2

解决方案


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


推荐阅读