小编自己码的通用型函数,支持各种常用视频格式,可满足常用需求,亲测效果和速度都不错。

想获取本文数据和完整代码的下载链接,请关注微信公众号"R语言和Python学堂",并回复发文日期"20181103"。

最近在帮着处理实验上的一些视频,我们知道视频是由一帧一帧图片叠加而制成的。其中第一步就是要把视频中的图片提取出来,怎么做呢?

有人会说,网上应该有很多相关小软件可以做这个事情。仔细一想,大多数软件应该不能满足以后的需求,比如:批量处理视频,提取视频某段时间内的图片,每隔一段时间提取一张图片。。。

Google了一下,发现Python在处理视频方面表现非常优秀,多数都是基于OpenCV库的。为了解决我的需求,因此决定自己写个基于Python+OpenCV的通用函数,来解决以后在提取图片过程中的各种需求。

这个函数就是本文要介绍的video2frames()函数,功能就是从视频中提取图片,名称“video2frames”是我自己取的,还比较形象。现将它分享给大家,感兴趣的小伙伴们可以参考一下,完整代码附在文末。

1. 主要功能

这个函数有以下主要功能:

提取特定时间点图片,比如:提取视频第3秒, 第5秒,第9秒图片

设定提取的起始时刻,比如:从视频的第10秒开始提取

设定提取的终止时刻,比如:100秒后的视频不提取图片

设定每隔多少秒提取一张图片,比如:每隔2秒从视频中提取一张图片

2. 函数参数

video2frames()函数的原型为:

video2frames(pathIn='',

pathOut='',

only_output_video_info = False,

extract_time_points = None,

initial_extract_time = 0,

end_extract_time = None,

extract_time_interval = -1,

output_prefix = 'frame',

jpg_quality = 100,

isColor = True)

各参数的意义:

pathIn:视频的路径,比如:F:\python_tutorials\test.mp4

pathOut:设定提取的图片保存在哪个文件夹下,比如:F:\python_tutorials\frames\。如果该文件夹不存在,函数将自动创建它

only_output_video_info:如果为True,只输出视频信息(长度、帧数和帧率),不提取图片

extract_time_points:提取的时间点,单位为秒,为元组数据,比如,(2, 3, 5)表示只提取视频第2秒, 第3秒,第5秒图片

initial_extract_time:提取的起始时刻,单位为秒,默认为0(即从视频最开始提取)

end_extract_time:提取的终止时刻,单位为秒,默认为None(即视频终点)

extract_time_interval:提取的时间间隔,单位为秒,默认为-1(即输出时间范围内的所有帧)

output_prefix:图片的前缀名,默认为frame,那么图片的名称将为frame_000001.jpg、frame_000002.jpg、frame_000003.jpg......

jpg_quality:设置图片质量,范围为0到100,默认为100(质量最佳)

isColor:如果为False,输出的将是黑白图片

目前只支持输出jpg格式图片

3. 例子

下面来测试一下这个函数的功能:

设置only_output_video_info为True,将只输出视频信息,不提取图片

>>> pathIn = 'test.mp4'

>>> video2frames(pathIn, only_output_video_info=True)

only output the video information (without extract frames)::::::

Duration of the video: 5.28 seconds

Number of frames: 132

Frames per second (FPS): 25.0

可以看到,视频test.mp4的长度为5.28秒,共132帧,帧率为25.0

提取所有图片,并保存到指定文件夹下

>>> pathIn = 'test.mp4'

>>> pathOut = './frames1/'

>>> video2frames(pathIn, pathOut)

Converting a video into frames......

Write a new frame: True, 1/132

Write a new frame: True, 2/132

..............................

Write a new frame: True, 131/132

Write a new frame: True, 132/132

可以看到,视频的132帧图片全部提取到frames1文件夹下

设置extract_time_points参数,提取特定时间点的图片

>>> pathIn = 'test.mp4'

>>> pathOut = './frames2'

>>> video2frames(pathIn, pathOut, extract_time_points=(1, 2, 5))

Write a new frame: True, 1th

Write a new frame: True, 2th

Write a new frame: True, 3th

可以看到,只提取了第1秒,第2秒和第5秒图片

每隔一段时间提取图片,并设置初始时刻和终止时刻

>>> pathIn = 'test.mp4'

>>> pathOut = './frames3'

>>> video2frames(pathIn, pathOut,

initial_extract_time=1,

end_extract_time=3,

extract_time_interval = 0.5)

Converting a video into frames......

Write a new frame: True, 1th

Write a new frame: True, 2th

Write a new frame: True, 3th

Write a new frame: True, 4th

Write a new frame: True, 5th

可以看到,1到3秒内的视频每隔0.5秒提取图片,共5张图片(分别为1s, 1.5s, 2s, 2.5s, 3s时刻的图片)

设置jpg_quality参数,改变输出图片的质量

>>> pathOut = './frames4'

>>> pathIn = 'test.mp4'

>>> video2frames(pathIn, pathOut, extract_time_points=(0.3, 2), jpg_quality=50)

Write a new frame: True, 1th

Write a new frame: True, 2th

设置isColor参数为False,提取的照片将是黑白色

>>> pathOut = './frames5'

>>> pathIn = 'test.mp4'

>>> video2frames(pathIn, pathOut, extract_time_points=(0.3, 2), isColor=False)

Write a new frame: True, 1th

Write a new frame: True, 2th

video2frames()函数的功能测试到此结束。

4. 完整代码

函数为通用型的,因此代码较长,可能还存在可以优化的地方,仅供参考。

完整代码如下:

# -*- coding: utf-8 -*-

import os

import cv2 ##加载OpenCV模块

def video2frames(pathIn='',

pathOut='',

only_output_video_info = False,

extract_time_points = None,

initial_extract_time = 0,

end_extract_time = None,

extract_time_interval = -1,

output_prefix = 'frame',

jpg_quality = 100,

isColor = True):

'''

pathIn:视频的路径,比如:F:\python_tutorials\test.mp4

pathOut:设定提取的图片保存在哪个文件夹下,比如:F:\python_tutorials\frames1\。如果该文件夹不存在,函数将自动创建它

only_output_video_info:如果为True,只输出视频信息(长度、帧数和帧率),不提取图片

extract_time_points:提取的时间点,单位为秒,为元组数据,比如,(2, 3, 5)表示只提取视频第2秒, 第3秒,第5秒图片

initial_extract_time:提取的起始时刻,单位为秒,默认为0(即从视频最开始提取)

end_extract_time:提取的终止时刻,单位为秒,默认为None(即视频终点)

extract_time_interval:提取的时间间隔,单位为秒,默认为-1(即输出时间范围内的所有帧)

output_prefix:图片的前缀名,默认为frame,图片的名称将为frame_000001.jpg、frame_000002.jpg、frame_000003.jpg......

jpg_quality:设置图片质量,范围为0到100,默认为100(质量最佳)

isColor:如果为False,输出的将是黑白图片

'''

cap = cv2.VideoCapture(pathIn) ##打开视频文件

n_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) ##视频的帧数

fps = cap.get(cv2.CAP_PROP_FPS) ##视频的帧率

dur = n_frames/fps ##视频的时间

##如果only_output_video_info=True, 只输出视频信息,不提取图片

if only_output_video_info:

print('only output the video information (without extract frames)::::::')

print("Duration of the video: {} seconds".format(dur))

print("Number of frames: {}".format(n_frames))

print("Frames per second (FPS): {}".format(fps))

##提取特定时间点图片

elif extract_time_points is not None:

if max(extract_time_points) > dur: ##判断时间点是否符合要求

raise NameError('the max time point is larger than the video duration....')

try:

os.mkdir(pathOut)

except OSError:

pass

success = True

count = 0

while success and count < len(extract_time_points):

cap.set(cv2.CAP_PROP_POS_MSEC, (1000*extract_time_points[count]))

success,image = cap.read()

if success:

if not isColor:

image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ##转化为黑白图片

print('Write a new frame: {}, {}th'.format(success, count+1))

cv2.imwrite(os.path.join(pathOut, "{}_{:06d}.jpg".format(output_prefix, count+1)), image, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame as JPEG file

count = count + 1

else:

##判断起始时间、终止时间参数是否符合要求

if initial_extract_time > dur:

raise NameError('initial extract time is larger than the video duration....')

if end_extract_time is not None:

if end_extract_time > dur:

raise NameError('end extract time is larger than the video duration....')

if initial_extract_time > end_extract_time:

raise NameError('end extract time is less than the initial extract time....')

##时间范围内的每帧图片都输出

if extract_time_interval == -1:

if initial_extract_time > 0:

cap.set(cv2.CAP_PROP_POS_MSEC, (1000*initial_extract_time))

try:

os.mkdir(pathOut)

except OSError:

pass

print('Converting a video into frames......')

if end_extract_time is not None:

N = (end_extract_time - initial_extract_time)*fps + 1

success = True

count = 0

while success and count < N:

success,image = cap.read()

if success:

if not isColor:

image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

print('Write a new frame: {}, {}/{}'.format(success, count+1, n_frames))

cv2.imwrite(os.path.join(pathOut, "{}_{:06d}.jpg".format(output_prefix, count+1)), image, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame as JPEG file

count = count + 1

else:

success = True

count = 0

while success:

success,image = cap.read()

if success:

if not isColor:

image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

print('Write a new frame: {}, {}/{}'.format(success, count+1, n_frames))

cv2.imwrite(os.path.join(pathOut, "{}_{:06d}.jpg".format(output_prefix, count+1)), image, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame as JPEG file

count = count + 1

##判断提取时间间隔设置是否符合要求

elif extract_time_interval > 0 and extract_time_interval < 1/fps:

raise NameError('extract_time_interval is less than the frame time interval....')

elif extract_time_interval > (n_frames/fps):

raise NameError('extract_time_interval is larger than the duration of the video....')

##时间范围内每隔一段时间输出一张图片

else:

try:

os.mkdir(pathOut)

except OSError:

pass

print('Converting a video into frames......')

if end_extract_time is not None:

N = (end_extract_time - initial_extract_time)/extract_time_interval + 1

success = True

count = 0

while success and count < N:

cap.set(cv2.CAP_PROP_POS_MSEC, (1000*initial_extract_time+count*1000*extract_time_interval))

success,image = cap.read()

if success:

if not isColor:

image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

print('Write a new frame: {}, {}th'.format(success, count+1))

cv2.imwrite(os.path.join(pathOut, "{}_{:06d}.jpg".format(output_prefix, count+1)), image, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame as JPEG file

count = count + 1

else:

success = True

count = 0

while success:

cap.set(cv2.CAP_PROP_POS_MSEC, (1000*initial_extract_time+count*1000*extract_time_interval))

success,image = cap.read()

if success:

if not isColor:

image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

print('Write a new frame: {}, {}th'.format(success, count+1))

cv2.imwrite(os.path.join(pathOut, "{}_{:06d}.jpg".format(output_prefix, count+1)), image, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame as JPEG file

count = count + 1

##### 测试

pathIn = 'test.mp4'

video2frames(pathIn, only_output_video_info = True)

pathOut = './frames1/'

video2frames(pathIn, pathOut)

pathOut = './frames2'

video2frames(pathIn, pathOut, extract_time_points=(1, 2, 5))

pathOut = './frames3'

video2frames(pathIn, pathOut,

initial_extract_time=1,

end_extract_time=3,

extract_time_interval = 0.5)

pathOut = './frames4/'

video2frames(pathIn, pathOut, extract_time_points=(0.3, 2), isColor = False)

pathOut = './frames5/'

video2frames(pathIn, pathOut, extract_time_points=(0.3, 2), jpg_quality=50)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本公众号。

感谢您的阅读!想了解更多有关Python技巧,请关注我的微信公众号“R语言和Python学堂”,我将定期更新相关文章。

python提取图片文字视频教学_用Python提取视频中的图片相关推荐

  1. Python办公自动化实战 05 | Python-docx库:Python与Word的完美结合_ 利用代码实现Word中插入图片

    一.专题内容简介 本专题主要介绍Python针对Word办公自动化如何利用Python代码动态向Word中插入图片.​并且对格式做简单设定. 二.专题案例效果 最终运行效果如下: 三.专题代码实现 3 ...

  2. word 图片导入不翻转_如何在Microsoft Word中翻转图片

    word 图片导入不翻转 While Microsoft Word isn't known for its photo-editing abilities, it does have some bas ...

  3. python读取图片文字为表格_利用python将图片转换成excel文档格式

    前言 本文主要介绍了关于利用python将图片转换成excel文档的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 实现步骤 读取图像,获取图像每个像素点的RGB值: 根据 ...

  4. python音频转文字腾讯_使用Python三步完成文本到语音的转换

    重磅干货,第一时间送达 一篇文章带你了解文本到语音转换步骤 在<这篇文章>中,我们有简单提到"文本语音转换"的相关内容,本文将继续讲述其详细实现步骤. 这里小编将介绍文 ...

  5. 基于python的公众号课堂教学_基于Python的微信公众号数据挖掘分析

    基于Python的微信公众号数据挖掘分析 华南农业大学电子工程学院 王 建 黄宁香 [期刊名称]电子世界 [年(卷),期]2019(000)011 [总页数]3 运用Python网络爬虫技术对某时事类 ...

  6. python提取视频字幕_利用Python提取视频中的字幕(文字识别)

    我的CSDN博客id:qq_39783601,昵称是糖潮丽子~辣丽 从今天开始我会陆续将数据分析师相关的知识点分享在这里,包括Python.机器学习.数据库等等. 今天来分享一个Python小项目! ...

  7. python 提取图片的某个颜色_使用python提取图片中的主体颜色

    上次国庆节去谷歌开发者大会,体验了很多有趣的人工智能项目. 其中有一个颜色匹配的环节,叫做"AI调色板,解码缤纷艺术世界",让我觉得很有意思,回来后,我计划自己实现一个类似的功能. ...

  8. python文字验证码识别_利用python进行验证码识别(预处理部分)

    # -*- coding: utf-8 -*- """Created on Thu Feb 1 15:52:05 2018@author: Administrator&q ...

  9. python诞生的时间地点人物_用Python来计算任意视频中各人物的出镜时间!这项目值50K吗?...

    用Python来计算任意视频中各人物的出镜时间!这项目值50K吗? 简介当我开始接触深度学习时,学到的第一件事就是图像分类.这个话题非常有趣,包括我在内的很多人都沉浸在它的魅力之中.但是在我处理图像分 ...

最新文章

  1. 安装 SQL Server 2008 R2 的硬件和软件要求(转)
  2. pandas.Series.multiply()含义解释
  3. MySQL当您插入列无效的数据插入
  4. Asp.net上传文件限制,在大于5M的时候出现DNS解析错误,解决方法。
  5. Android中基于Socket的网络通信
  6. 龙图 VP 李翀:数据化运营及云计算下的运维
  7. 诗与远方:无题(九十二)
  8. Elasticsearch学习之基本核心概念
  9. 单位载质量能量消耗量_Ekg指标计算案例之电动物流车
  10. Verilog语言语句介绍
  11. osgEarth的Rex引擎原理分析(二十五)地形瓦片大小尺寸和LOD的关系
  12. 谷歌股价跌的越多,我们买的越多
  13. Java-TCP通信(实现多发多收、群聊功能),BS通信源码
  14. 惠普HP Deskjet 1010 打印机驱动
  15. C++ API设计 - 读书笔记(XMind)
  16. java位运算符和位运算表达式
  17. bake lightmap in unity 2
  18. 梦一样——十一月英语总结
  19. SFX Silhouette for mac功能介绍(影视后期特效软件)
  20. 口袋进化服务器维护,口袋进化平民攻略

热门文章

  1. HOW TO:在 Visual C++ .NET 中从 System::String* 转换为 Char*
  2. swagger2 注解说明文档
  3. 【其他技术类文章】如何用mapinfo绘制地图
  4. SQL2K数据库开发二十一之索引操作创建索引
  5. sshclientCRT连接linux使用技巧
  6. spring MVC要注意的地方 2
  7. objective-c block 旧版详解
  8. C99中的变长数组(VLA)
  9. GridView控件RowDataBound事件中获取列字段的几种方法(转)
  10. windows怎么用gpu跑python程序_在GPU(windows)上运行Theano的命令