开发者

Python实现视频分帧的方法分享

开发者 https://www.devze.com 2023-03-25 09:27 出处:网络 作者: 像风一样的男人@
目录下载依赖实现方法一方法二方法三下载依赖 pip install opencv-python=php=4.0.0.21
目录
  • 下载依赖
  • 实现
    • 方法一
    • 方法二
    • 方法三

下载依赖

pip install opencv-python=php=4.0.0.21

实现

方法一

def video_to_frames(video_path, outPutDirName):
    """
    抽取视频帧存为图片
    :param video_path:
    :param outPutDirName:
    :return:
    """
    times = 0

    # 提取视频的频率,每1帧提取一个
    frame_frequency = 1

    # 如果文件目录不存在则创建目录
    if not os.path.exists(outPutDirName):
        os.makedirs(outPutDirName)

    # 读取视频帧
    camera = cv2.VideoCapture(video_path)

    while True:
        times = times + 1
        res, image = camera.read()
        if not res:
            print('not res , not image')
            break
        # 按照设置间隔存储视频帧
        if times % frame_frequency == 0:
            create_path = os.path.join(outPutDirName, f"{str(times)}.jpg")
          http://www.devze.com  cv2.imwrite(create_path, image)

    logger.info('图片提取结束')
    # 释放摄像头设备
    camera.release()


def image_to_video(image_path, media_path, fps):
    '''
    图片合成视频函数
    :param image_path: 图片路径
    :param media_path: 合成视频保存路径
    :return:
    '''
 javascript   # 获取图片路径下面的所有图片名称
    image_names = os.listdir(image_path)
    # 对提取到的图片名称进行排序
    image_names.sort(key=lambda n: int(n[:-4]))
    # 设置写入格式
    fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
    # 设置每秒帧数
    fps = fps
    # 读取第一个图片获取大小尺寸,因为需要转换成视频的图片大小尺寸是一样的
    image = Image.open(os.path.join(image_path, image_names[0]))
    # 初始化媒体写入对象
    media_writer = cv2.VideoWriter(media_path, fourcc, fps, image.size)
    # 遍历图片,将每张图片加入视频当中
    for image_name in image_names:
        im = cv2.imread(os.path.join(image_path, image_name))
        media_writer.write(im)
    # 释放媒体写入对象
    media_writer.release()
    logger.info('无声视频写入完成!')

方法二

import numpy as np
import cv2
import os
import sys
def cut(video_file, target_dir):
    cap = cv2.VideoCapture(video_file)  # 获取到一个视频
    isOpened = cap.isOpened  # 判断是否打开
    # 为单张视频,以视频名称所javascript谓文件名,创建文件夹
    temp = os.path.split(video_file)[-1]
    dir_name = temp.split('.')[0]

    single_pic_store_dir = os.path.join(target_dir, dir_name编程)
    if not os.path.exists(single_pic_store_dir):
        os.mkdir(single_pic_store_dir)


    i = 0
    while isOpened:

        i += 1

        (flag, frame) = cap.read()  # 读取一张图像

        fileName = 'image' + str(i) + ".jpg"
        if (flag == True):
            # 以下三行 进行 旋转
            #frame = np.rot90(frame, -1)


            #print(fileName)
            # 设置保存路径
            save_path = os.path.join(single_pic_store_dir, fileName)
            #print(save_path)
            res = cv2.imwrite(save_path, frame, [cv2.IMWRITE_JPEG_QUALITY, 70])
            #print(res)
        else:
            break

    return single_pic_store_dir

if __name__ == '__main__':
    video_file = 'I:/crack.avi'
    cut(video_file, 'I:/data/')

方法三

#!/usr/bin/env python
import cv2
numer = 18
cap=cv2.VideoCapture("/home/linux/work/python/video/"+str(numer)+".mp4")

if cap.isOpened():
    ret,frame=cap.read()
els开发者_JS开发e:
    ret = False

n=0
i=0
timeF = 40
path='/home/linux/work/python/video/'+str(numer)+'/{}'
while ret:
    n = n + 1
    ret,frame=cap.read()
    if (n%timeF == 0) :
        i = i+1
        print(i)
        filename=str(numer)+"_"+str(i)+".jpg"
        cv2.imwrite(path.format(filename),frame)
    cv2.waitKey(1)

cap.release()

补充

除了视频分帧,Python还可以将帧合成视频流,下面是实现代码

#!/usr/bin/env python
import cv2

img = cv2.imread('/home/linux/work/python/img/1_475.jpg')
imginfo = img.shape
size = (imginfo[1],imginfo[0])
print(size)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
videoWrite = cv2.VideoWriter('/home/linux/work/python/2.mp4',fourcc,10,size) 

for i in range(475,2208):
    filename = '/home/linux/work/python/img/1_'+str(i)+'.jpg'
    img = cv2.imread(filename,1)
    videoWrite.write(img)  
    print(i)

videoWrite.release()
print('end')

到此这篇关于Python实现视频分帧的方法分享的文章就介绍到这了,更多相关Python视频分帧内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号