作者:R语言和Python学堂
链接:https://www.jianshu.com/p/e3c04d4fb5f3

这个函数就是本文要介绍的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.jpgframe_000002.jpgframe_000003.jpg......

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

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

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

3. 例子

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

  • 设置only_output_video_infoTrue,将只输出视频信息,不提取图片
>>> 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 opencv提取视频中的图片的更多相关文章

  1. pyhthon Opencv截取视频中的图片

    import os import cv2 ##加载OpenCV模块 def video2frames(pathIn='', pathOut='', imgname='', only_output_vi ...

  2. python+opencv选出视频中一帧再利用鼠标回调实现图像上画矩形框

    最近因为要实现模板匹配,需要在视频中选中一个目标,然后框出(即作为模板),对其利用模板匹配的方法进行检测.于是需要首先选出视频中的一帧,但是在利用摄像头读视频的过程中我唯一能想到的方法就是: 1.在视 ...

  3. PHP提取字符串中的图片地址

    PHP提取字符串中的图片地址 $str='<p><img border="0" src="upfiles/2009/07/1246430143_1.jp ...

  4. Java 添加、提取PDF中的图片

    Spire.Cloud.SDK for Java提供了PdfImagesApi接口可用于添加图片到PDF文档addImage().提取PDF中的图片extractImages(),具体操作步骤和Jav ...

  5. 50行Python代码实现视频中物体颜色识别和跟踪(必须以红色为例)

    目前计算机视觉(CV)与自然语言处理(NLP)及语音识别并列为人工智能三大热点方向,而计算机视觉中的对象检测(objectdetection)应用非常广泛,比如自动驾驶.视频监控.工业质检.医疗诊断等 ...

  6. opencv 读取视频内容写入图片帧

    现在主要把自己平时用到的opencv功能记录到博客,一方面方便自己有时间来回顾,另一方便提供给大家一个参考. opencv 读取视频内容,把视频帧每一帧写成图片,存入电脑中.这个步骤是许多数据处理的基 ...

  7. C#正则表达式通过HTML提取网页中的图片src

    目前在做HoverTreeCMS项目中有处理图片的部分,参考了一下网上案例,自己写了一个获取内容中的图片地址的方法. 可以先看看效果:http://tool.hovertree.com/a/zz/im ...

  8. Python抓取网页中的图片到本地

    今天在网上找了个从网页中通过图片URL,抓取图片并保存到本地的例子: #!/usr/bin/env python # -*- coding:utf- -*- # Author: xixihuang # ...

  9. 利用Effmpeg 提取视频中的音频(mp3)

    在B站看到一个up发的病名为爱的钢琴曲,感觉很好听,然后当然是要加入歌单啊.然而不知道怎么转换成mp3,找来找去找到了EFFmpeg 这篇只是达到了我简单的需求,以后可能会有EFFmpeg更详细的使用 ...

随机推荐

  1. 004-行为型-01-策略模式(Strategy)

    一.概述 定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户.需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可 ...

  2. SqStack进制计算

    基于SqStack 进制计算 #include<malloc.h> #include<stdio.h> #include<stdlib.h> typedef int ...

  3. 零基础学Python-第一章 :Python介绍和安装-02.Python的发展历史与版本

    pthhon3.0对开发者带来了麻烦,因为2.0个3.0的程序并不是兼容的. 目前python3.0已经变成了真正的主力 官方版本和发行版 发行版会把常用的科学计算的包也给继承进来.这样就不用考虑包和 ...

  4. RHEL7 的注册

    RHEL7 的注册 2016年09月12日 20:37:19 wojiushiwoba 阅读数 13002更多 分类专栏: 嵌入式linux   版权声明:本文为博主原创文章,遵循CC 4.0 BY- ...

  5. 【kubernetes 自带监控】 container级别cadvisor+kubelet,集群级别apiserver

    apiserver https://feisky.gitbooks.io/kubernetes/components/apiserver.html kube-apiserver 支持同时提供 http ...

  6. Linux之sudo免密码操作

    使用普通用户只需特权命令是需要输入密码,然后在五分钟以内只需命令可以免密码,下面设置免密码操作 系统环境查看 切换至root用户 sudo -i #需要输入密码 修改sudoers文件 #增加一行 y ...

  7. Ubuntu18安装虚拟机virtualbox

    环境查看 安装虚拟机 apt install virtualbox 图形化界面启动 virtualbox 其余创建虚拟机和安装和在Windows安装配置一样,不详述.

  8. [概率DP][消元法][CF24D]损坏的机器人

    Description 有一只坏了的机器人站在一个\(n\times m\)的网格里,初始位置在\((x,y)\).现在每个单位时间内它会随机选左右下三个方向走,如果它随机的方向会走出网格就不会往这个 ...

  9. SQL Server 数据库清空ldf日志文件

    USE [master] ALTER DATABASE [DB_Develop] SET RECOVERY SIMPLE WITH NO_WAIT ALTER DATABASE [DB_Develop ...

  10. java当中JDBC当中请给出一个SQLServer DataSource and SingleTon例子

    [学习笔记] 5.SQLServer DataSource and SingleTon: import net.sourceforge.jtds.jdbcx.*;import java.sql.*;i ...