本程序主要講視頻轉化爲圖片
創建video_to_images.py
#-*- coding: utf-8 -*-
#使用本程序的方法:
#1. 安裝python3
#2. 安裝numpy, 命令 pip3 install numpy
#3. 安裝opencv-python, 命令:pip3 install opencv-python
#4. 將該腳本放置在存儲視頻的文件夾中,利用python執行此腳本。
import os
import sys
filedir = os.path.dirname(sys.argv[0]) #獲取腳本所在目錄
os.chdir(filedir) #將腳本所在的目錄設置爲工作目錄
wdir = os.getcwd()
print('當前工作目錄:{}\n'.format(wdir)) #打印當前工作目錄
import numpy as np
import cv2 as cv;
import re
from math import ceil
def video_to_image(video_path):
print('\n-----------------------------------------------------------------------------')
print('正在處理視頻:{}\n'.format(video_path))
video_dir = os.path.dirname(video_path)
video_name = os.path.basename(video_path)
image_dir = re.sub('\.','_',video_name)
image_dir = os.path.join(video_dir, image_dir)
if not os.path.exists(image_dir):
os.mkdir(image_dir)
cap = cv.VideoCapture(video_path)
# Define the codec and create VideoWriter object
fps = cap.get(5) #視頻幀率
width = cap.get(3)
height = cap.get(4)
sample_rate = round(fps) #採樣率,目前設置爲每秒取1幀。
#print("視頻 {} 的幀率爲:{:.2f} 分辨率爲:{} ✖ {}".format(video_path, fps, width, height))
print("視頻 {} 的幀率爲:{} 分辨率爲:{} * {}".format(video_path, fps, width, height))
n=0
new_img_num = 0
old_img_num = 0
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
#cv.imshow('frame1', frame)
n=n+1
if n%sample_rate == 1:
image_name = video_name+'_'+str(n)+'.jpg'
image_path = os.path.join(image_dir, image_name)
if os.path.exists(image_path):
print('{} 已經存在。'.format(image_path))
old_img_num += 1
else :
print(image_path)
cv.imwrite(image_path,frame)
new_img_num += 1
if cv.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
print('視頻處理完畢,共{}幀。每{}幀採1張,可生成{}張圖片。\n'.format(n, sample_rate, ceil(n/sample_rate)))
print('此前已有圖片{}張,本次生成{}張。\n'.format(old_img_num, new_img_num))
ext = ('.h264', '.MOV')
#遍歷工作目錄,並對其中指定格式的視頻文件進行處理。
# def search(path):
# for p in os.listdir(path):
# p = os.path.join(path, p)
# if os.path.isdir(p):
# search(p)
# elif p.endswith(ext):
# video_to_image(p)
# search(wdir)
for dirpath, dirname, filename in os.walk(wdir):
for f in filename:
if f.endswith(ext):
video_path = os.path.join(dirpath, f)
video_to_image(video_path)