pyhthon Opencv截取视频中的图片
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截取视频中的图片的更多相关文章
- Python opencv提取视频中的图片
作者:R语言和Python学堂链接:https://www.jianshu.com/p/e3c04d4fb5f3 这个函数就是本文要介绍的video2frames()函数,功能就是从视频中提取图片,名 ...
- python 从视频中提取图片,并保存在硬盘上
使用python的moviepy库来提取视频中的图片,按照视频每帧一个图片的方式来保存. extract images from video, than save them to disk from ...
- opencv 读取视频内容写入图片帧
现在主要把自己平时用到的opencv功能记录到博客,一方面方便自己有时间来回顾,另一方便提供给大家一个参考. opencv 读取视频内容,把视频帧每一帧写成图片,存入电脑中.这个步骤是许多数据处理的基 ...
- python+opencv选出视频中一帧再利用鼠标回调实现图像上画矩形框
最近因为要实现模板匹配,需要在视频中选中一个目标,然后框出(即作为模板),对其利用模板匹配的方法进行检测.于是需要首先选出视频中的一帧,但是在利用摄像头读视频的过程中我唯一能想到的方法就是: 1.在视 ...
- Opencv在视频中静态、动态方式绘制矩形框ROI
Opencv视频处理中的目标跟踪经常用到要在视频上画一个矩形框ROI,标注出要跟踪的物体,这里介绍两种在视频中绘制矩形框的方法,一种是"静态的",一种是"动态的" ...
- Webdriver中实现区域截图的方式以及如何截取frame中的图片
import java.awt.Rectangle;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOE ...
- opencv 将视频分解成图片和使用本地图片合成视频
代码如下: // cvTest.cpp : Defines the entry point for the console application. #include "stdafx.h&q ...
- (转载)[FFmpeg]使用ffmpeg从各种视频文件中直接截取视频图片
你曾想过从一个视频文件中提取图片吗?在Linux下就可以,在这个教程中我将使用ffmpeg来从视频中获取图片. 什么是ffmpeg?What is ffmpeg? ffmpeg是一个非常有用的命令行程 ...
- 基础学习笔记之opencv(6):实现将图片生成视频
基础学习笔记之opencv(6):实现将图片生成视频 在做实验的过程中.难免会读视频中的图片用来处理,相反将处理好的图片又整理输出为一个视频文件也是非经常常使用的. 以下就来讲讲基于opencv的C+ ...
随机推荐
- 18-Flutter移动电商实战-首页_火爆专区商品接口制作
1.获取接口的方法 在service/service_method.dart里制作方法.我们先不接收参数,先把接口调通. Future getHomePageBeloConten() async{ ...
- java 8 学习三(Stream API)
集合讲的是数据,流讲的是计算. 流的数据处理功能支持类似于数据库的操作,以及函数式编程语言中的常用操作,如filter. map. reduce. find. match. sort等. 流操作可以顺 ...
- 使用blessed-contrib 开发专业的终端dashboard
blessed-contrib 是blessed 的一个扩展包,以前有说过blessed(一个方便的开发cli 的工具) 我们使用blessed-contrib可以开发专业的终端dashboard 功 ...
- 使用openrc 管理容器中的服务
对于后台任务一般是不建议在容器中运行的,但是如果我们为了简化应用的部署,可能会使用后台任务进行服务的管理,类似的 工具很多,supervisor,systemd , init.d 同时对于docker ...
- LVS 的负载均衡调度算法
LVS 的负载均衡调度算法 1.轮叫调度 (Round Robin) ( rr ) 调度器通过“ 轮叫 ”调度算法将外部请求按顺序轮流分配到集群的真实服务器上,它均等地对待每一台服务器,而不管服务器上 ...
- CGLIB和Java动态代理的区别(笔记)
java常用知识点: 1.Java动态代理只能够对接口进行代理,不能对普通的类进行代理(因为所有生成的代理类的父类为Proxy,Java类继承机制不允许多重继承):CGLIB能够代理普通类:2.Jav ...
- hive基础知识三
1. 基本查询 注意 SQL 语言大小写不敏感 SQL 可以写在一行或者多行 关键字不能被缩写,也不能分行 各子句一般要分行写 使用缩进提高语句的可读性 1.1 全表和特定列查询 全表查询 selec ...
- CentOS7.4下安装部署HAProxy高可用群集
目录第一部分 实验环境第二部分 搭建配置web服务器第三部分 安装配置haproxy服务器第四部分 测试验证第五部分 haproxy配置相关详细解释 第一部分 实验环境1.一台harpoxy调度服务器 ...
- 树形dp专题总结
树形dp专题总结 大力dp的练习与晋升 原题均可以在网址上找到 技巧总结 1.换根大法 2.状态定义应只考虑考虑影响的关系 3.数据结构与dp的合理结合(T11) 4.抽直径解决求最长链的许多类问题( ...
- cloudstack 安装 install for ubuntu
准备工作环境信息 修改dns配置 设置阿里源root@sh-saas-cs-manager-online-01:~# mv /etc/apt/sources.list /etc/apt/sources ...