前言
如若你也是一位职场宝爸\宝妈,欢迎关注微公众号“荪荪陪娃”,在技术的道路上,我们一起抱团取暖交流学习科学育儿。
摘要
作为一个职业病+懒癌的人,你还在为孩子痴迷看的动画片而担心视力发愁吗?那么策略是,将动画片变成绘本。难不成还是一一截图?
NO, NO, NO,作为懒癌的我们,可以写代码呀,将动画片转为音频+纸质书啊,这样即保护了视力,还培养了爱阅读的好习惯,何乐而不为呢?
废话少说,上代码。
实现部分
import cv2
import os
def create_dir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
def getFile_name(file_dir, ext='.jpg'):
# file_dir = self.xmlRoot
L = []
for root, dirs, files in os.walk(file_dir):
# print(files)
for file in files:
if os.path.splitext(file)[1] == ext:
pathlist = os.path.join(root, file)
L.append(pathlist) # L.append(os.path.splitext(file)[0]) # L.append(os.path.join(root, file))
return L
def singleVideo2Img(videoName, dst_dir):
sub_video, namext = os.path.split(videoName)
name, _ = os.path.splitext(namext)
_, sub_name = os.path.split(sub_video)
dst_sub = os.path.join(dst_dir, sub_name)
create_dir(dst_sub)
vc = cv2.VideoCapture(videoName) # 读入视频文件
c = 1
timeF = 1000 # 视频帧计数间隔频率
if vc.isOpened(): # 判断是否正常打开
rval, frame = vc.read()
else:
rval = False
# try:
while rval: # 循环读取视频帧
rval, frame = vc.read()
if (c % timeF == 0): # 每隔timeF帧进行存储操作
d = int(c / 1000) + 1
imgName = name + "_" + str(d) + '.jpg'
imgpath = os.path.join(dst_sub, imgName)
cv2.imwrite(imgpath, frame) # 存储为图像
print(d)
c = c + 1
# cv2.waitKey(1)
def video_2_img(invideo_dir, dst_dir):
video_names = getFile_name(invideo_dir, '.avi') # '.mp4'
for videoName in video_names:
print(videoName)
sub_video, namext = os.path.split(videoName)
name, _ = os.path.splitext(namext)
_, sub_name = os.path.split(sub_video)
dst_sub = os.path.join(dst_dir, sub_name)
imgs_dir = os.path.join(dst_sub, name)
create_dir(imgs_dir)
vc = cv2.VideoCapture(videoName) # 读入视频文件
c = 1
timeF = 100 #50 # 视频帧计数间隔频率
if vc.isOpened(): # 判断是否正常打开
print('nihao! ')
rval, frame = vc.read()
# cv2.imshow('frame', frame)
# cv2.waitKey(10)
print('open video OK! ')
print(rval)
else:
rval = False
# print('not open')
# try:
while rval: # 循环读取视频帧
rval, frame = vc.read()
# cv2.imshow('frame', frame)
# cv2.waitKey(10)
if frame is None:
print('example')
break
if (c % timeF == 0): # 每隔timeF帧进行存储操作
d = int(c / timeF) + 1
imgName = name + "_" + str(d) + '.jpg'
imgpath = os.path.join(imgs_dir, imgName)
# print(imgpath)
# cv2.imwrite(imgpath, frame) # 存储为图像
cv2.imencode('.jpg', frame)[1].tofile(imgpath)
print(d)
c = c + 1
# cv2.waitKey(1)
if __name__ == "__main__":
invideo_dir = r"H:\糖果\yakka dee单词卡\第二季视频MP4"
dst_dir = r"H:\糖果\yakka dee单词卡\第二季视频MP4_imgs"
video_2_img(invideo_dir, dst_dir)
# videoName = r"H:\糖果\yakka dee单词卡\第二季视频MP4\Yakka.Dee.S01E01.Banana.mp4"
# singleVideo2Img(videoName, dst_dir)