python目标检测将视频按照帧率切除成图片

python目标检测将视频按照帧率切除成图片

python目标检测将视频按照帧率切除成图片,并且允许放入多个多个视频

完整代码如下:

bash 复制代码
import os
import cv2

class VideoSplit:
    """
    将视频分帧为图片
    source_path: 视频文件存储地址
    result_path: 图片结果文件保存地址
    frame: 帧率,每frame帧保存一张图片
    """

    def __init__(self, source_path, result_path, frame=10):
        self.source_path = source_path
        if not os.path.exists(self.source_path):
            raise Exception("源文件路径不存在!")

        self.result_path = result_path
        self.frame = frame
        if not os.path.exists(self.result_path):
            os.makedirs(self.result_path)
            print("创建文件夹{},".format(self.result_path))

    def split_video(self):
        video_list = os.listdir(self.source_path)
        for i, name in enumerate(video_list):
            video_list[i] = os.path.join(self.source_path, name)
            basename = name.split('.')[0]
            video_result_path = os.path.join(self.result_path, basename)
            if not os.path.exists(video_result_path):
                os.makedirs(video_result_path)
                print("创建子文件夹{},".format(basename))
            cap = cv2.VideoCapture(video_list[i])
            print("视频{}开始分帧...".format(name))

            sum = 0
            i = 0
            while True:
                ret, frame = cap.read()
                if not ret:
                    break
                sum += 1
                # 保存图片
                if sum == self.frame:
                    sum = 0
                    i += 1
                    imgname = basename + '_' + str(i) + '.jpg'
                    imgPath = os.path.join(video_result_path, imgname)
                    cv2.imwrite(imgPath, frame)
                    print(imgname)
            print("{}视频文件提取完成".format(basename))
        print("完成")

if __name__ == "__main__":
    source_path = r'C:\Users\video'
    result_path = r'C:\Users\result'
    tst = VideoSplit(source_path, result_path)
    tst.split_video()

注意:尽量手动创建两个文件夹video、result

相关推荐
兵慌码乱10 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵11 小时前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio15 小时前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户03321266636716 小时前
使用 Python 从零创建 Word 文档
python
Csvn21 小时前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽1 天前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817531 天前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱2 天前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei2 天前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python