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. centos 7 开启外网方法端口方法

    firewall-cmd --zone=public --add-port=80/tcp --permanent  开启80端口 systemctl stop firewalld.service sy ...

  2. Spring搬迁

      Spring简介 加载bean流程 Bean的生命周期 双亲委派 自定义类加载器 Spring事务 异步Async Spring设计模式 Spring单例 SpringMVC流程   备注:app ...

  3. Hibernate学习:Exception in thread "main" java.lang.NullPointerException

    1.在学习Hibernate多对多关系的时候遇到了一下异常: 主函数出现了空指针异常: public static void testadd() { Session session = Hiberna ...

  4. 为知笔记docker 版本运行

    最近为知提供了服务端的docker 运行,因为是全家桶,镜像偏大,但是使用还很不错,对于少于5人的可以免费使用 docker-compose 文件 version: "3" ser ...

  5. 使用google autoservice 自动生成java spi 描述文件

    spi 是一种服务发现的标准,对于开发中我们通常需要编写 META-INF/services 文件夹中定义的类. google auto 中的autoservice 可以帮助我们生成对应的配置,很方便 ...

  6. asyncapi 指南

    asyncapi 是可以用来创建异步机器可读定义api的指南,我们可以用来创建事件驱动的架构. 说明 asyncapi 的定义类似openapi,目前指南版本为2.0,很值得学习下 参考资料 http ...

  7. 第04组alpha冲刺(4/4)

    队名:斗地组 组长博客:地址 作业博客:Alpha冲刺(4/4) 各组员情况 林涛(组长) 过去两天完成了哪些任务: 1.分配展示任务 2.收集各个组员的进度 3.写博客 展示GitHub当日代码/文 ...

  8. K8s configMap原理介绍

    给容器内应用程序传递参数的实现方式: 1. 将配置文件直接打包到镜像中,但这种方式不推荐使用,因为修改配置不够灵活. 2. 通过定义Pod清单时,指定自定义命令行参数,即设定 args:[" ...

  9. GoCN每日新闻(2019-11-09)

    GoCN每日新闻(2019-11-09) 1. Go语言发行10周年庆祝 https://blog.golang.org/10years2. 容器中某Go服务GC停顿经常超过100ms排查 https ...

  10. linux高性能服务器编程 (七) --Linux服务器程序规范

    第七章 LInux 服务器程序规范 1)linux服务器程序一般以后台进程形式运行.后台进程又称为守护进程,是没有控制终端的,所以不会受到外界的干扰.守护进程的父进程通常是init进程(PID为1的进 ...