video.py OpenCv例程阅读
#!/usr/bin/env python '''
Video capture sample. Sample shows how VideoCapture class can be used to acquire video
frames from a camera of a movie file. Also the sample provides
an example of procedural video generation by an object, mimicking
the VideoCapture interface (see Chess class). 'create_capture' is a convinience function for capture creation,
falling back to procedural video in case of error. Usage:
video.py [--shotdir <shot path>] [source0] [source1] ...' sourceN is an
- integer number for camera capture
- name of video file
- synth:<params> for procedural video Synth examples:
synth:bg=../cpp/lena.jpg:noise=0.1
synth:class=chess:bg=../cpp/lena.jpg:noise=0.1:size=640x480 Keys:
ESC - exit
SPACE - save current frame to <shot path> directory ''' import numpy as np
import cv2
from time import clock
from numpy import pi, sin, cos
import common class VideoSynthBase(object):
def __init__(self, size=None, noise=0.0, bg = None, **params):
self.bg = None
self.frame_size = (640, 480)
if bg is not None:
self.bg = cv2.imread(bg, 1)
h, w = self.bg.shape[:2]
self.frame_size = (w, h) if size is not None:
w, h = map(int, size.split('x'))
self.frame_size = (w, h)
self.bg = cv2.resize(self.bg, self.frame_size) self.noise = float(noise) def render(self, dst):
pass def read(self, dst=None):
w, h = self.frame_size if self.bg is None:
buf = np.zeros((h, w, 3), np.uint8)
else:
buf = self.bg.copy() self.render(buf) if self.noise > 0.0:
noise = np.zeros((h, w, 3), np.int8)
cv2.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
buf = cv2.add(buf, noise, dtype=cv2.CV_8UC3)
return True, buf def isOpened(self):
return True class Chess(VideoSynthBase):
def __init__(self, **kw):
super(Chess, self).__init__(**kw) w, h = self.frame_size self.grid_size = sx, sy = 10, 7
white_quads = []
black_quads = []
for i, j in np.ndindex(sy, sx):
q = [[j, i, 0], [j+1, i, 0], [j+1, i+1, 0], [j, i+1, 0]]
[white_quads, black_quads][(i + j) % 2].append(q)
self.white_quads = np.float32(white_quads)
self.black_quads = np.float32(black_quads) fx = 0.9
self.K = np.float64([[fx*w, 0, 0.5*(w-1)],
[0, fx*w, 0.5*(h-1)],
[0.0,0.0, 1.0]]) self.dist_coef = np.float64([-0.2, 0.1, 0, 0])
self.t = 0 def draw_quads(self, img, quads, color = (0, 255, 0)):
img_quads = cv2.projectPoints(quads.reshape(-1, 3), self.rvec, self.tvec, self.K, self.dist_coef) [0]
img_quads.shape = quads.shape[:2] + (2,)
for q in img_quads:
cv2.fillConvexPoly(img, np.int32(q*4), color, cv2.CV_AA, shift=2) def render(self, dst):
t = self.t
self.t += 1.0/30.0 sx, sy = self.grid_size
center = np.array([0.5*sx, 0.5*sy, 0.0])
phi = pi/3 + sin(t*3)*pi/8
c, s = cos(phi), sin(phi)
ofs = np.array([sin(1.2*t), cos(1.8*t), 0]) * sx * 0.2
eye_pos = center + np.array([cos(t)*c, sin(t)*c, s]) * 15.0 + ofs
target_pos = center + ofs R, self.tvec = common.lookat(eye_pos, target_pos)
self.rvec = common.mtx2rvec(R) self.draw_quads(dst, self.white_quads, (245, 245, 245))
self.draw_quads(dst, self.black_quads, (10, 10, 10)) classes = dict(chess=Chess) presets = dict(
empty = 'synth:',
lena = 'synth:bg=../cpp/lena.jpg:noise=0.1',
chess = 'synth:class=chess:bg=../cpp/lena.jpg:noise=0.1:size=640x480'
) def create_capture(source = 0, fallback = presets['chess']):
'''source: <int> or '<int>|<filename>|synth [:<param_name>=<value> [:...]]'
'''
source = str(source).strip()
chunks = source.split(':')
# hanlde drive letter ('c:', ...)
if len(chunks) > 1 and len(chunks[0]) == 1 and chunks[0].isalpha():
chunks[1] = chunks[0] + ':' + chunks[1]
del chunks[0] source = chunks[0]
try: source = int(source)
except ValueError: pass
params = dict( s.split('=') for s in chunks[1:] ) cap = None
if source == 'synth':
Class = classes.get(params.get('class', None), VideoSynthBase)
try: cap = Class(**params)
except: pass
else:
cap = cv2.VideoCapture(source)
if 'size' in params:
w, h = map(int, params['size'].split('x'))
cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, w)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, h)
if cap is None or not cap.isOpened():
print 'Warning: unable to open video source: ', source
if fallback is not None:
return create_capture(fallback, None)
return cap if __name__ == '__main__':
import sys
import getopt print __doc__ args, sources = getopt.getopt(sys.argv[1:], '', 'shotdir=')
args = dict(args)
shotdir = args.get('--shotdir', '.')
if len(sources) == 0:
sources = [ 0 ] caps = map(create_capture, sources)
shot_idx = 0
while True:
imgs = []
for i, cap in enumerate(caps):
ret, img = cap.read()
imgs.append(img)
cv2.imshow('capture %d' % i, img)
ch = 0xFF & cv2.waitKey(1)
if ch == 27:
break
if ch == ord(' '):
for i, img in enumerate(imgs):
fn = '%s/shot_%d_%03d.bmp' % (shotdir, i, shot_idx)
cv2.imwrite(fn, img)
print fn, 'saved'
shot_idx += 1
cv2.destroyAllWindows()
第133行:create_capture(source = 0, fallback = presets['chess']) 有两个参数 source 用于指示在哪里获取视频源。fallback ------------
声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')
总结 开启数据采集设备并返回 控制句柄。
video.py OpenCv例程阅读的更多相关文章
- camshift.py OpenCv例程阅读
源码在这 #!/usr/bin/env python ''' Camshift tracker ================ This is a demo that shows mean-shif ...
- common.py OpenCv例程阅读
#!/usr/bin/env python ''' This module contais some common routines used by other samples. ''' import ...
- Video Processing subsystem例程分析
Video Processing subsystem例程分析 1.memory_ss模块 slave端口: S00: 连接设备: microblaze_ss----M_AXI_DC 时钟来源: S01 ...
- OpenCV例程实现人脸检测
前段时间看的OpenCV,其实有很多的例子程序,参考代码值得我们学习,对图像特征提取三大法宝:HOG特征,LBP特征,Haar特征有一定了解后. 对本文中的例子程序刚开始没有调通,今晚上调通了,试了试 ...
- 【双目备课】OpenCV例程_stereo_calib.cpp解析
stereo_calib是OpenCV官方代码中提供的最正统的双目demo,无论数据集还是代码都有很好实现. 一.代码效果: 相关的内容包括28张图片,1个xml和stereo_calib.cpp的代 ...
- python中 __init__.py的例程
__init__.py一般是为空,用在一个python目录中,标识该目录是一个python的模块包 先上来看一个例子: .: test1 test2 test_init.py ./test1: tim ...
- Overview of the High Efficiency Video Coding (HEVC) Standard阅读笔记
1.INTRODUCTION High Efficiency Video Coding(HEVC) <-> H.265 MPEG-4 Advanced Video Coding(AVC) ...
- OpenCV 例程
采集图片显示视频: #include <iostream> #include <opencv2/opencv.hpp> using namespace std; using n ...
- Opencv Cookbook阅读笔记(四):用直方图统计像素
灰度直方图的定义 灰度直方图是灰度级的函数,描述图像中该灰度级的像素个数(或该灰度级像素出现的频率):其横坐标是灰度级,纵坐标表示图像中该灰度级出现的个数(频率). #include <open ...
随机推荐
- openwrt gstreamer实例学习笔记(六. gstreamer Pads及其功能)
一:概述 如我们在Elements一章中看到的那样,Pads是element对外的接口.数据流从一个element的source pad到另一个element的sink pad.pads的功能(cap ...
- 【bzoj4554】[Tjoi2016&Heoi2016]游戏
现在问题有硬石头和软石头的限制 所以要对地图进行预处理 分行做,把有#隔开的*(x)形成联通块的存储下来. 分列作,把有#隔开的*(x)形成联通块的存储下来. 求出所有的行联通个数和列联通个数 作为二 ...
- Provided Maven Coordinates must be in the form 'groupId:artifactId:version'.
[hadoop@hadoop1 bin]$ ./spark-shell --packages org.mongodb.spark:mongo-spark-connector_2.10-2.2.1 Ex ...
- Flume 和 kafka的区别和对比
定义: Flume:是Cloudera提供的一个分布式的海量日志采集.聚合和传输的系统: Kafka:是一种高吞吐量的分布式发布订阅消息系统: 各特点: 场景: Flume主要是和HDFS\HBase ...
- mysql 数据库连接
1.需要mysql驱动包:mysql-connector-java-5.1.7-bin.jar 2. package com.jmu.ccjoin.web.controller; import jav ...
- (linux)likely和unlikely函数
在Linux内核中likely和unlikely函数有两种(只能两者选一)实现方式,它们的实现原理稍有不同,但作用是相同的,下面将结合linux-2.6.38.8版本的内核代码来进行讲解. 1.对 ...
- Fabric原理剖析
Fabric架构 image.png Fabric网络 image.png Fabric模块 image.png Fabric交易流 根据Hyperledger Fabric 1.0架构, ...
- [Selenium] 操作浏览器前进后退
driver.get("http://1.com"); driver.navigate().to("http://2.com"); driver.navigat ...
- MDZX——张能传
「你们到底要干什么?!」——8012年7月13日 张能于MDZX ———————————— 序章 ———————————— 话说天下大势,分久必合,合久必分. 他肩扛99米大砍刀,站在MDZX大门对面 ...
- servlet中的servletURL,servletURI和servletPath
String servletURL=request.getservletURL(); url:站点名+当前web应用名+(目录名)+页面名 String servletURI=reques ...