欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python提取视频帧图片实例代码

程序员文章站 2022-06-16 13:06:06
为了从视频中提取每一帧图片,编写python脚本实现该功能video_path为指定的视频路径interval为指定分割视频是是否跳帧,默认不跳帧,即全部分割width, height 为指定对分割帧...

为了从视频中提取每一帧图片,编写python脚本实现该功能

video_path为指定的视频路径

interval为指定分割视频是是否跳帧,默认不跳帧,即全部分割

width, height 为指定对分割帧图片调整大小,默认不调整

该脚本自动对帧图片编号,设置为7位编码,最多可分割9999999帧图片,即92小时的30fps视频

# !/usr/bin/env python
# -*- coding: utf-8 -*-
# ============================================================
# @date    : 2021/12/08 14:40:31
# @author  : lishan
# @email   : lishan@st.xatu.edu.com
# @file    : extract.py
# @ide     : pycharm
# @func    : extract video image
# ============================================================
import os.path
import time
import cv2
 
video_path = "./assets/intersection.mp4"
idx1 = video_path.rfind('/')
idx2 = video_path.rfind('.')
save_path = "./assets/" + video_path[idx1+1:idx2]
if os.path.exists(save_path):
    pass
else:
    os.mkdir(save_path)
 
cap = cv2.videocapture(video_path)
fps = int(cap.get(cv2.cap_prop_fps))
print('fps:{:.2f}'.format(fps))
rate = cap.get(5)
frame_num = cap.get(7)
duration = frame_num/rate
print('video total time:{:.2f}s'.format(duration))
 
# width, height = 1920, 1080
cnt = 0
num = 0
# interval = int(fps) * 4
interval = 1
process_num = frame_num // interval
print('process frame:{:.0f}'.format(process_num))
 
t0 = time.time()
while cap.isopened():
    ret, frame = cap.read()
    if ret:
        cnt += 1
        if cnt % interval == 0:
            num += 1
            # frame = cv.resize(frame, (width, height))
            cv2.imwrite(save_path + "/%07d.jpg" % num, frame)
            remain_frame = process_num - num
            t1 = time.time() - t0
            t0 = time.time()
            print("processing %07d.jpg, remain frame: %d, remain time: %.2fs" % (num, remain_frame, remain_frame * t1))
    else:
        break
    if cv2.waitkey(1) & 0xff == 27:
        break
 
cap.release()
cv2.destroyallwindows()
print("done")

Python提取视频帧图片实例代码

到此这篇关于python提取视频帧图片实例代码的文章就介绍到这了,更多相关python提取视频帧图片内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!