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 ...
随机推荐
- PHP生成excel(3)
这一节主要是设置背景颜色.边框.字体大小.表格宽度 效果图 代码如下 <?php header("Content-Type:text/html;charset=utf-8") ...
- ZOJ 3230 Solving the Problems(数学 优先队列啊)
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3230 Programming is fun, Aaron is ...
- ln: 正在创建指向“asm-arm”的符号链接“asm”: 不支持的操作
原因是不能在windows共享目录编译,将待编译的uboot源码copy到home目录
- Python开发【深浅拷贝】
1.==与is a = [1,2] b = [1,2] a==b >>>True a is b >>>False 2.拷贝与非拷贝 拷贝:原则上就是把数据分离出来, ...
- WPF新手之如何将数据绑定到TreeView
看过许多例子,全是绑定到类的,没人说如何绑定到某个对象,偏偏我这个绝对的新手就是要绑定到一个对象,只能自己摸索了: 首先要将数据绑定到容器,有以下几个默认条件:①元数据必须包装在List或者Obser ...
- sendmessage传递数组
1.在初始化数组尤其是需要每次都初始化的时候,很多同学使用循环来进行,这样不但速度慢,而且写起来也很长.所以现在提供一个函数来实现这个功能... 原型:extern void *memset(void ...
- Axure Base 08 动态面板的用途
写了几个Axure教程之后发现,可能教程的起点有些高了,过分的去讲效果的实现,而忽略了axure功能以及基础元件的使用,那么从这个教程开始,把这些逐渐的展开讲解. 关于动态面板 动态面板是axure原 ...
- filename extension
题目描述 Please create a function to extract the filename extension from the given path,return the extra ...
- MYSQL进阶学习笔记四:MySQL存储过程之定义条件,处理过程及存储过程的管理!(视频序号:进阶_11,12)
知识点五:MySQL存储过程之定义条件和处理过程及存储过程的管理(11,12) 定义条件和处理: 条件的定义和处理可以用来定义在处理过程中遇到的问题时相应的处理步骤. DECLARE CONTINUE ...
- contents属性
CALayer 有一个属性叫做contents,这个属性的类型被定义为id,意味着它可以是任何类型的对象.在这种情况下,你可以给contents属性赋任何值,你的app仍然能够编译通过.但是,在实践中 ...