【工具篇】使用OpenCV播放视频并截取图片

1.主要用途: 获取目标检测数据集时,录像获取视频,然后播放该视频并截取其图像;
2.运行方法: 在安装好依赖包后,更换成自己的视频文件路径,运行main程序即可;
3.播放后使用说明: 运行播放后,按下q键退出,s键保存当前帧图片;按k可暂停视频,再按s保存该帧图像;
说明一:.亲测在Ubuntu系统下,MP4格式文件的截取;
说明二: 保存图像的路径在当前目录会自动生成一个文件夹进行保存;不清楚的可以先运行该程序,按s保存即清除保存路径
说明三: rotate代表是否对原视频进行旋转
若有什么问题,欢迎留言交流。。

import cv2
from pathlib import Path
import glob, re ,os
import imutils

def increment_path(path, exist_ok=False, sep='', mkdir=False):
    # Increment file or directory path,
    path = Path(path)  # os-agnostic
    n = ''
    if path.exists() and not exist_ok:
        suffix = path.suffix
        path = path.with_suffix('')
        dirs = glob.glob(f"{path}{sep}*")  # similar paths
        matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
        i = [int(m.groups()[0]) for m in matches if m]  # indices
        n = max(i) + 1 if i else 2  # increment number
        path = Path(f"{path}{sep}{n}{suffix}")  # update path
    dir = path if path.suffix == '' else path.parent  # directory
    if not dir.exists() and mkdir:
        dir.mkdir(parents=True, exist_ok=True)  # make directory
    return path, str(n)

#====== init pic save path=======#
# 1. process the input video name
def init_savepath(video_path=None):
    assert video_path is not None, 'please check the video path'
    v_path = video_path
    inp_videoname = os.path.split(v_path)[-1]  # 得到输入视频的名字,如video.mp4
    videoname, video_type = inp_videoname.split('.') # return str

    # 2. init the cutpic save dir
    project_name = f'save_dir/video_cutpic/'   #  parents savedir , eg. save_dir/video_cutpic
    childdir_savename = f'{videoname}_dir'  # child_savedir name ,eg video3_dir
    exist_ok = False
    save_dir, savedir_num = increment_path(Path(project_name) / childdir_savename, exist_ok=exist_ok) # return type :str
    Path(str(save_dir)).mkdir(parents= True, exist_ok=True)
    return v_path, save_dir, childdir_savename, savedir_num
#================================#

def videocut_process(ori_videopath=None, rotate =False, angle=None):
    assert ori_videopath is not None, 'please check the video path'
    print(' k to pause the video, q to quit the process')
    video_path, save_dir, childdir_savename, savedir_num = init_savepath(video_path=ori_videopath)
    pic_startnum = 0
    cap = cv2.VideoCapture(video_path)
    fps = cap.get(cv2.CAP_PROP_FPS) # 原视频的fps
    while (cap.isOpened()):
        ret, frame = cap.read()

        if ret:
            height, width = frame.shape[:2]
            if rotate:
                frame = imutils.rotate_bound(frame, angle)

            cv2.imshow('frame', frame)
            k = cv2.waitKey(1)
            filename = str(Path(save_dir) / f'{childdir_savename}{savedir_num}_{pic_startnum}.jpg')  # savefilename
            if k == ord('q'):  # 按q键退出
                break
            elif k == ord('s'): # 保存当前帧图片
                cv2.imwrite(filename, frame)
                print(f'Save pic{pic_startnum} success')
                pic_startnum +=1

            elif k == ord('k'): # 点击k暂停,
                print('pause now, press k to continue, press s to save the pic')
                k2 = cv2.waitKey(0)
                if k2 ==ord('s'):
                    cv2.imwrite(filename, frame)
                    print(f'Save pic{pic_startnum} success')
                    pic_startnum +=1
        else:
            cap.release()
            cv2.destroyAllWindows()
            break

# 需要的文件, 1. 视频文件.mp4   2.保存的路径
# 保存文件 使用Increment进行保存
if __name__ == '__main__':
    video_path = 'video2.mp4'
    rotate_bool, angle_val = True, -90 # 是否旋转,旋转角度
    videocut_process(ori_videopath=video_path, rotate=rotate_bool, angle=angle_val)

你可能感兴趣的:(笔记,python,opencv)