# -- coding:utf-8 --
'''
视频按帧保存成图片,图片保存到脚本目录下的image文件夹下,以视频名称命名各自文件夹
V1.2(20191108)
1.支持文件夹-文件夹-视频
2.支持文件夹-视频
3.支持-视频
V1.1(20190829)
修改说明:
1.支持中文视频名称
'''
import cv2
import multiprocessing as nps
import numpy as np
import logging
import os
import time
logger = logging.getLogger("log")
logger.setLevel(logging.DEBUG)
# logger的setLevel是最根本的
fh = logging.FileHandler('log' + time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) + '.log')
# 如果没有这个,就不会输出到文件
fh.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
def video_frame(mv_path):
try:
vc = cv2.VideoCapture(mv_path) # 读入视频文件
c = 1
if vc.isOpened(): # 判断是否正常打开
rval, frame = vc.read()
else:
rval = False
timeF =2 # 视频帧计数间隔频率
n=1
while rval: # 循环读取视频帧
rval, frame = vc.read()
if (c % timeF == 0): # 每隔timeF帧进行存储操作
#cv2.imwrite('image/' + str(c) + '.jpg', frame) # 存储为图像
image_file=mv_path.split('\\')[-1].split('.')[0]
image_file1=mv_path.split('\\')[-2]
dir_name = sc_file+'/' + image_file1 + '/'+image_file + '/'
save_path=sc_file+'/' +image_file1 + '/' + image_file + '/' + str(image_file) + '_' + str(n) + '.jpg'
try:
if os.path.exists(dir_name)!=True: # 路径不存在才创建
os.makedirs(dir_name)
logger.info('创建目录,保存《' + str(image_file1) + '》下的“' +str(image_file)+"”视频的第"+str(c)+'帧,保存为“' + save_path.split('/')[-1]+'”')
#cv2.imwrite(save_path, frame) # 存储为图像
try:
cv2.imencode('.jpg', frame)[1].tofile(save_path) # #路径不能为中文解决方法
except:
logger.error('《' + str(image_file1) + '》下的“' +str(image_file)+"”视频的第"+str(c)+'帧,保存为“' + save_path.split('/')[-1]+'”'+ '失败……')
Lower_resolution(save_path)
n+=1
else:
logger.info('目录存在,保存《' + str(image_file1) + '》下的“' +str(image_file)+"”视频的第"+str(c)+'帧,保存为“' + save_path.split('/')[-1]+'”')
try:
cv2.imencode('.jpg', frame)[1].tofile(save_path) # #路径不能为中文解决方法
except:
logger.error('《' + str(image_file1) + '》下的“' +str(image_file)+"”视频的第"+str(c)+'帧,保存为“' + save_path.split('/')[-1]+'”'+ '失败……')
Lower_resolution(save_path)
n += 1
except Exception as a:
logger.error('《' + str(image_file1) + '》下的“' +str(image_file)+"”视频的第"+str(c)+'帧' + str(a))
c = c + 1
cv2.waitKey(1)
vc.release()
except Exception as a:
logger.error("输入的可能不是视频"+str(a))
def Lower_resolution(file_path): # 降低分辨率(720*720)
try:
# 修改之后的图片大
size_ = (720, 720)
img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1) # 路径不能为中文解决方法
im2 = cv2.resize(img, size_, interpolation=cv2.INTER_CUBIC)
# saved_path = r'D:\Python\python3\picture processing\哈哈\kjfhkj_5453.JPG'
# cv2.imwrite(saved_path, im2) #保存
cv2.imencode('.jpg', im2)[1].tofile(file_path) # #路径不能为中文解决方法
except:
logger.error('《'+ file_path.split('/')[-2]+'》的'+file_path.split('/')[-1]+'图片异常,删除')
os.remove(file_path)
def PathList(filepath):
try:
if os.path.isdir(filepath):
wwfile=[]
mvimage=[]
imagepath=[]
for i in os.listdir(filepath):
fulldirct = os.path.join(filepath, i)
if os.path.isdir(fulldirct): # 入参需要是绝对路径
wwfile.append(fulldirct)
else:
mvimage.append(fulldirct)
if len(wwfile)!=0:
for i in wwfile:
for n in os.listdir(i):
imagepath.append(os.path.join(i,n))
for i in imagepath:
video_frame(i)
if len(mvimage)!=0:
for i in mvimage:
video_frame(i)
else:
video_frame(filepath)
except Exception as a:
logger.error("输入的可能不是视频文件"+str(a))
def Run(path):
dir=path.split("\\")[-1]
if sc_file not in os.listdir(os.getcwd()): # 文件夹名称不存在才创建
os.mkdir(os.getcwd() + '/' + sc_file+'/')
PathList(path)
else:
PathList(path)
sc_file='image'
print('\n')
path = input('请将保存所有视频的文件夹拖入窗口,并点击回车!!!!!\n\n')
Run(path)
input('Press Enter to exit...')
'''
path = r'D:\Python\python3\取帧\mv'
sc_file='image'
Run(path)
'''
视频按帧保存成图片,然后再调整图像分辨率为720*720
猜你喜欢
转载自blog.csdn.net/qq_42846555/article/details/100141780
今日推荐
周排行