python cv2 封装一个视频IO_todo

import cv2
import os
import time
class VideoFileIO(object):
    '''
    NAME
        The Class of Video'IO

    PACKAGE CONTENTS
        extract_frames: Video extract picture
    '''
    def __init__(self):
        pass

    def extract_frames(self, file_path:str, extract_fps:int=None, save_path:str=None):
        self.cap = cv2.VideoCapture(file_path)
        out_basename = os.path.splitext(os.path.basename(file_path))[0]
        # assert self.cap.isOpened()
        if not self.cap.isOpened():
            print("can not open the video!")
            exit(1) # 等价于 return 1 异常
            pass
        save_path = save_path if save_path is not None else out_basename
        os.makedirs(save_path) if not os.path.exists(save_path) else None
        if extract_fps is None:
            extract_fps = int(self.cap.get(cv2.CAP_PROP_FPS))
            pass
        fourcc = int(self.cap.get(cv2.CAP_PROP_FOURCC))
        frams = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        count = 0
        while self.cap.isOpened():
            ret, frame = self.cap.read()
            if frame is None:
                print("extract frames is finish!")
                break
            if count % extract_fps == 0:
                cv2.imwrite(os.path.join(save_path, out_basename + '_' + str(count).zfill(len(str(frams))) +'.jpg'), frame)
                pass
            count+=1
            pass
        self.cap.release()
        return fourcc, frams

    def synthetic_video(self, file_dir:str, save_dir:str=r'.', size:tuple=(1920, 1080), fps:int=30, max_save_frames:int=100):
        if not os.path.isdir(file_dir):
            print("file_dir is not a dir!")
            exit(1)
            pass
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
            pass
        file_list = os.listdir(file_dir)
        assert len(file_list)!=0, "None file"
        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        cap = cv2.VideoWriter(os.path.join(save_dir, "res_"+os.path.basename(file_dir)+'.mp4'), fourcc, fps, size)
        assert cap.isOpened()
        for i in range(0, min(len(file_list), len(file_list))):
            frame_path = os.path.join(file_dir, file_list[i])
            if os.path.isfile(frame_path):
                frame = cv2.imread(frame_path)
                frame = cv2.resize(frame, size)
                cap.write(frame)
                pass
            pass
        cap.release()
        pass        

    def record_video(self, save_dir:str=r'.', size:tuple=(1280, 1024), fps:int=25):
        cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
        if not cap.isOpened():
            print("can not open the video!")
            exit(1) # 等价于 return 1 异常
            pass

        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
            pass

        runtime = time.localtime()
        runtime = [runtime.tm_year, runtime.tm_mon, runtime.tm_mday, runtime.tm_hour, runtime.tm_min, runtime.tm_sec]
        file_name = '_'.join('%s' %id for id in runtime) + '.mp4'

        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        vw = cv2.VideoWriter(os.path.join(save_dir, file_name), fourcc, fps, (width, height))

        while cap.isOpened():
            ret, frame = cap.read()
            if ret:
                vw.write(frame)
                cv2.imshow('capture', frame)
                if cv2.waitKey(10) & 0xFF == ord('q'): # 按键盘Q键退出
                    break
            else:
                continue
        cv2.destroyAllWindows()
        cap.release()
        vw.release()
        pass
    pass

cvid = VideoFileIO()
# cvid.extract_frames(file_path=r'VID_20220702_142227.mp4', extract_fps=1)
# cvid.synthetic_video(file_dir=r'visualized_test_results')
cvid.record_video()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智能之心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值