opencv 在Python中将视频转换为帧- 1 FPS

jfgube3f  于 2023-10-24  发布在  Python
关注(0)|答案(3)|浏览(112)

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

gzjq41n41#

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

nwlls2ji2#

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

# 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)。

juud5qan

juud5qan3#

这是我发现的最好的代码。

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

相关问题