import os
import cv2 ##加载OpenCV模块 def video2frames(pathIn='',
pathOut='',
imgname='',
only_output_video_info = False,
extract_time_points = None,
initial_extract_time = 0,
end_extract_time = None,
extract_time_interval = -1,
output_prefix = 'img', 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) ##视频的帧率
print(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, "{}_{}.jpg".format(output_prefix, imgname)), 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, "{}_{}.jpg".format(output_prefix, imgname)), 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, "{}_{}.jpg".format(output_prefix, imgname)), 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, "{}_{}.jpg".format(output_prefix,imgname)), 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, "{}_{}.jpg".format(output_prefix, imgname)), image, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]) # save frame as JPEG file
count = count + 1 if __name__ == "__main__":
pathIn = 'C:/Users/Administrator/www/video_back/video_back/upload/1.mp4'
pathOut = 'C:/Users/Administrator/www/video_back/video_back/upload/'
imgname = 'dog'
video2frames(pathIn,pathOut,imgname,extract_time_points=(1,))

pyhthon Opencv截取视频中的图片的更多相关文章

  1. Python opencv提取视频中的图片

    作者:R语言和Python学堂链接:https://www.jianshu.com/p/e3c04d4fb5f3 这个函数就是本文要介绍的video2frames()函数,功能就是从视频中提取图片,名 ...

  2. python 从视频中提取图片,并保存在硬盘上

    使用python的moviepy库来提取视频中的图片,按照视频每帧一个图片的方式来保存. extract images from video, than save them to disk from ...

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

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

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

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

  5. Opencv在视频中静态、动态方式绘制矩形框ROI

    Opencv视频处理中的目标跟踪经常用到要在视频上画一个矩形框ROI,标注出要跟踪的物体,这里介绍两种在视频中绘制矩形框的方法,一种是"静态的",一种是"动态的" ...

  6. Webdriver中实现区域截图的方式以及如何截取frame中的图片

    import java.awt.Rectangle;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOE ...

  7. opencv 将视频分解成图片和使用本地图片合成视频

    代码如下: // cvTest.cpp : Defines the entry point for the console application. #include "stdafx.h&q ...

  8. (转载)[FFmpeg]使用ffmpeg从各种视频文件中直接截取视频图片

    你曾想过从一个视频文件中提取图片吗?在Linux下就可以,在这个教程中我将使用ffmpeg来从视频中获取图片. 什么是ffmpeg?What is ffmpeg? ffmpeg是一个非常有用的命令行程 ...

  9. 基础学习笔记之opencv(6):实现将图片生成视频

    基础学习笔记之opencv(6):实现将图片生成视频 在做实验的过程中.难免会读视频中的图片用来处理,相反将处理好的图片又整理输出为一个视频文件也是非经常常使用的. 以下就来讲讲基于opencv的C+ ...

随机推荐

  1. (尚028)Vue_案例_交互删除

    删除一条;1.鼠标移入移除这一条时颜色有变化 2.删除当前的todo ================================================================= ...

  2. 使用Maven创建一个普通java项目

    1.创建项目: 使用Maven目的是是我们能够轻松的管理各种别人写过的包 创建好之后,我们去找我们所需要的包:在mvnrepository.com中找自己所需要的包 例子: 最后将依赖写入pom.xm ...

  3. vector的使用注意事项

    示例1: #include "iostream" #include "vector" using namespace std; int main(void) { ...

  4. nuxtjs在vue组件中使用window对象编译报错的解决方法

    我们知道nuxtjs是做服务端渲染的,他有很多声明周期是运行在服务端的,以及正常的vue声明周期mounted之前均是在服务端运行的,那么服务端是没有比如window对象的location.navag ...

  5. 利用python爬虫爬取图片并且制作马赛克拼图

    想在妹子生日送妹子一张用零食(或者食物类好看的图片)拼成的马赛克拼图,因此探索了一番= =. 首先需要一个软件来制作马赛克拼图,这里使用Foto-Mosaik-Edda(网上也有在线制作的网站,但是我 ...

  6. SpringBoot + CXF快速实现SOAP WebService(支持Basic Auth)

    唠叨两句 讲真,SOAP跟现在流行的RESTful WebService比起来显得很难用.冗余的XML文本信息太多,可读性差,它的请求信息有时很难手动构造,不太好调试.不过说归说,对某些企业用户来说S ...

  7. myeclipse的安装与破解

    myeclipe安装和破解一直困扰我很长时间,我又是尴尬症的人,不破解就是不行,花费一天时间终于搞定是怎么破解的. 一:首先myeclipse的官方下载网站www.myeclipsecn.com/do ...

  8. plsql excel导入报错:未发现数据源名称并且未指定默认驱动程序

        1.情景展示 使用plsql的odbc导入器,导入excel数据时,报错信息如下: anydac 未发现数据源名称如何处理 2.原因分析 操作系统的问题,我的是64位的系统,plsql支持32 ...

  9. Mybatis27题

    1.什么是Mybatis? Mybatis是一个半ORM(对象关系映射)框架,它内部封装了JDBC,开发时只需要关注SQL语句本身,不需要花费精力去处理加载驱动.创建连接.创建statement等繁杂 ...

  10. Vue/小程序/小程序云+Node+Mongo开发微信授权、支付和分享

    大家好,我是河畔一角,今天给大家介绍我的第三门实战课程:基于微信开发的H5.小程序和小程序云的授权.支付和分享专项课程. 一.这一次为什么会选择微信支付和分享的课题呢? 金庸的小说中曾提到:有人的地方 ...