文件夹下所有视频按指定秒提取
本帖最后由 16713720339 于 2022-12-13 19:45 编辑之前的帖子发的是按照指定帧提取图片,但是使用下来发现太慢了,因为要解析所有的帧。
之前的帖子 https://www.52pojie.cn/forum.php?mod=viewthread&tid=1726138&page=1#pid45082722
新特点:
1、这次用的指定秒提取,免得解析每一帧,减少时间
2、可以输入的是文件夹地址,也可以是单个视频文件的地址
import cv2
import os
#图片截取
def get_frame_from_video(video_name, frame_time, img_dir, img_name):
"""
get a specific frame of a video by time in milliseconds
:param video_name: video name
:param frame_time: time of the desired frame
:param img_dir: path which use to store output image
:param img_name: name of output image
:return: None
"""
vidcap = cv2.VideoCapture(video_name)
# Current position of the video file in milliseconds.
vidcap.set(cv2.CAP_PROP_POS_MSEC, frame_time - 1)
# read(): Grabs, decodes and returns the next video frame
success, image = vidcap.read()
if not os.path.exists(img_dir):
os.makedirs(img_dir)
if success:
# save frame as JPEG file
#cv2.imwrite(img_dir + sep + img_name, image)
cv2.imencode('.jpg', image).tofile(img_dir +'/'+ str(img_name)+'.jpg') ##正确方法
# cv2.imshow("frame%s" % frame_time, image)
# cv2.waitKey()
#得到相应的秒值列表
def qvmiaozhi(zongmiao,jiangemiao):
a=[]
miao = 1
while miao<=zongmiao:
a.append(miao)
miao = int(miao) + int(jiangemiao)
return a
#获取视频的秒时长
def get_video_miaoshu(filename):
cap = cv2.VideoCapture(filename)
if cap.isOpened():
rate = cap.get(5)
frame_num =cap.get(7)
duration = frame_num/rate
return duration
return -1
if __name__ == "__main__":
path_lujing = input('输入文件夹路径')
im_file = path_lujing
jiangemiao = input('间隔时间')
wenjian_houzhui = os.path.splitext(path_lujing)[-1] #获取输入的后缀
#判断输入的是一个文件夹路径还是一个文件
if wenjian_houzhui == '':
for im_name in os.listdir(im_file): #im_name 完整名字带后缀
wenjian_ming = os.path.splitext(im_name) #
wenjian_houzhui = os.path.splitext(im_name)[-1]
#if wenjian_houzhui == 'mp4' or 'avi':
#print(im_name)
path = path_lujing +'/'+ im_name
#print(path)
img_dir = path_lujing + wenjian_ming + '/'
#img_name = '666'
#jiangemiao = 10
zongmiao = get_video_miaoshu(path)
maio_lie = qvmiaozhi(zongmiao,jiangemiao)
#get_frame_from_video(video_name, frame_time, img_dir, img_name)
print(im_name+'有'+str(zongmiao)+'秒')
#print(maio_lie)
print('保存'+str(len(maio_lie))+'张图片')
n = 1
for i in maio_lie:
get_frame_from_video(path, i*1000, img_dir, i)
print('已经保存完成'+str(n)+'张')
n = n + 1
else:
print('单文件')
path = path_lujing
#print(path)
wenjian_ming = os.path.splitext(path)
img_dir = wenjian_ming + '/'
#img_name = '666'
#jiangemiao = 10
zongmiao = get_video_miaoshu(path)
maio_lie = qvmiaozhi(zongmiao,jiangemiao)
#get_frame_from_video(video_name, frame_time, img_dir, img_name)
print(path+'有'+str(zongmiao)+'秒')
#print(maio_lie)
print('保存'+str(len(maio_lie))+'张图片')
n = 1
for i in maio_lie:
get_frame_from_video(path, i*1000, img_dir, i)
print('已经保存完成'+str(n)+'张')
n = n + 1
本人小白,很想用,就是不会用。代码弄进去,也出错 哈哈哈太牛感谢分享 学习学习 多谢楼主分享,码下细细学习 收藏持续进行 学习学习 收藏为敬,感谢分享。 不是软件不会用,纯支持了
页:
[1]
2