#!/usr/bin/env python

'''
This module contais some common routines used by other samples.
''' import numpy as np
import cv2
import os
from contextlib import contextmanager
import itertools as it image_extensions = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.pbm', '.pgm', '.ppm'] class Bunch(object):
def __init__(self, **kw):
self.__dict__.update(kw)
def __str__(self):
return str(self.__dict__) def splitfn(fn):
path, fn = os.path.split(fn)
name, ext = os.path.splitext(fn)
return path, name, ext def anorm2(a):
return (a*a).sum(-1)
def anorm(a):
return np.sqrt( anorm2(a) ) def homotrans(H, x, y):
xs = H[0, 0]*x + H[0, 1]*y + H[0, 2]
ys = H[1, 0]*x + H[1, 1]*y + H[1, 2]
s = H[2, 0]*x + H[2, 1]*y + H[2, 2]
return xs/s, ys/s def to_rect(a):
a = np.ravel(a)
if len(a) == 2:
a = (0, 0, a[0], a[1])
return np.array(a, np.float64).reshape(2, 2) def rect2rect_mtx(src, dst):
src, dst = to_rect(src), to_rect(dst)
cx, cy = (dst[1] - dst[0]) / (src[1] - src[0])
tx, ty = dst[0] - src[0] * (cx, cy)
M = np.float64([[ cx, 0, tx],
[ 0, cy, ty],
[ 0, 0, 1]])
return M def lookat(eye, target, up = (0, 0, 1)):
fwd = np.asarray(target, np.float64) - eye
fwd /= anorm(fwd)
right = np.cross(fwd, up)
right /= anorm(right)
down = np.cross(fwd, right)
R = np.float64([right, down, fwd])
tvec = -np.dot(R, eye)
return R, tvec def mtx2rvec(R):
w, u, vt = cv2.SVDecomp(R - np.eye(3))
p = vt[0] + u[:,0]*w[0] # same as np.dot(R, vt[0])
c = np.dot(vt[0], p)
s = np.dot(vt[1], p)
axis = np.cross(vt[0], vt[1])
return axis * np.arctan2(s, c) def draw_str(dst, (x, y), s):
cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.CV_AA)
cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.CV_AA) class Sketcher:
def __init__(self, windowname, dests, colors_func):
self.prev_pt = None
self.windowname = windowname
self.dests = dests
self.colors_func = colors_func
self.dirty = False
self.show()
cv2.setMouseCallback(self.windowname, self.on_mouse) def show(self):
cv2.imshow(self.windowname, self.dests[0]) def on_mouse(self, event, x, y, flags, param):
pt = (x, y)
if event == cv2.EVENT_LBUTTONDOWN:
self.prev_pt = pt
if self.prev_pt and flags & cv2.EVENT_FLAG_LBUTTON:
for dst, color in zip(self.dests, self.colors_func()):
cv2.line(dst, self.prev_pt, pt, color, 5)
self.dirty = True
self.prev_pt = pt
self.show()
else:
self.prev_pt = None # palette data from matplotlib/_cm.py
_jet_data = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89,1, 1),
(1, 0.5, 0.5)),
'green': ((0., 0, 0), (0.125,0, 0), (0.375,1, 1), (0.64,1, 1),
(0.91,0,0), (1, 0, 0)),
'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65,0, 0),
(1, 0, 0))} cmap_data = { 'jet' : _jet_data } def make_cmap(name, n=256):
data = cmap_data[name]
xs = np.linspace(0.0, 1.0, n)
channels = []
eps = 1e-6
for ch_name in ['blue', 'green', 'red']:
ch_data = data[ch_name]
xp, yp = [], []
for x, y1, y2 in ch_data:
xp += [x, x+eps]
yp += [y1, y2]
ch = np.interp(xs, xp, yp)
channels.append(ch)
return np.uint8(np.array(channels).T*255) def nothing(*arg, **kw):
pass def clock():
return cv2.getTickCount() / cv2.getTickFrequency() @contextmanager
def Timer(msg):
print msg, '...',
start = clock()
try:
yield
finally:
print "%.2f ms" % ((clock()-start)*1000) class StatValue:
def __init__(self, smooth_coef = 0.5):
self.value = None
self.smooth_coef = smooth_coef
def update(self, v):
if self.value is None:
self.value = v
else:
c = self.smooth_coef
self.value = c * self.value + (1.0-c) * v class RectSelector:
def __init__(self, win, callback):
self.win = win
self.callback = callback
cv2.setMouseCallback(win, self.onmouse)
self.drag_start = None
self.drag_rect = None
def onmouse(self, event, x, y, flags, param):
x, y = np.int16([x, y]) # BUG
if event == cv2.EVENT_LBUTTONDOWN:
self.drag_start = (x, y)
if self.drag_start:
if flags & cv2.EVENT_FLAG_LBUTTON:
xo, yo = self.drag_start
x0, y0 = np.minimum([xo, yo], [x, y])
x1, y1 = np.maximum([xo, yo], [x, y])
self.drag_rect = None
if x1-x0 > 0 and y1-y0 > 0:
self.drag_rect = (x0, y0, x1, y1)
else:
rect = self.drag_rect
self.drag_start = None
self.drag_rect = None
if rect:
self.callback(rect)
def draw(self, vis):
if not self.drag_rect:
return False
x0, y0, x1, y1 = self.drag_rect
cv2.rectangle(vis, (x0, y0), (x1, y1), (0, 255, 0), 2)
return True
@property
def dragging(self):
return self.drag_rect is not None def grouper(n, iterable, fillvalue=None):
'''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx'''
args = [iter(iterable)] * n
return it.izip_longest(fillvalue=fillvalue, *args) def mosaic(w, imgs):
'''Make a grid from images. w -- number of grid columns
imgs -- images (must have same size and format)
'''
imgs = iter(imgs)
img0 = imgs.next()
pad = np.zeros_like(img0)
imgs = it.chain([img0], imgs)
rows = grouper(w, imgs, pad)
return np.vstack(map(np.hstack, rows)) def getsize(img):
h, w = img.shape[:2]
return w, h def mdot(*args):
return reduce(np.dot, args) def draw_keypoints(vis, keypoints, color = (0, 255, 255)):
for kp in keypoints:
x, y = kp.pt
cv2.circle(vis, (int(x), int(y)), 2, color)

第15行: Bunch函数是将传入 的参数作为一个字典便于查询使用。使用例程如下

>>> jack = Bunch(a=4,b=5,c=6)
>>> print(jack)
{'c': 6, 'a': 4, 'b': 5}
bokeyuan={"b":1,
"o":2,
"k":3,
"e":4,
"y":5,
"u":6,
"a":7,
"n":8,
}

该对象是用于将一个字典转化成对象的代码例如 现在想转化一个对象,我们通常会这样写

class Dict2Obj:
def __init__(self,bokeyuan):
self.b = bokeyuan['b']
self.o = bokeyuan['o']
self.k = bokeyuan['k']
self.e = bokeyuan['e']
self.y = bokeyuan['y']
self.u = bokeyuan['u']
self.a = bokeyuan['a']
self.n = bokeyuan['n']

但是在了解这个方法时候我们会这样写,

1 class Dict2Obj:
2 def __init__(self,bokeyuan):
3 self.__dict__.update(bokeyuan)

然后这样调用

jack = Dict2Obj(bokeyuan)

总结:__dict__用于显示该对象的所有字典元素。__dict__.update()用于更新或者添加元素。




第21行:该函数的作用是传入路径,os.path.split分割 路径名和文件名  os.path.splitext传入文件名.后缀 用于分割文件名和后缀

>>> os.path.split('jack/2/3/asd.jpg')
('jack/2/3', 'asd.jpg')
>>> os.path.splitext('asd.jpg')
('asd', '.jpg')



第26行: 矩阵相乘,然后每一行进行求和返回新的矩阵

第28行: 将第26行的结果开方

第31行: 3*3的矩阵 将第一行的元素乘以x第二行乘以x第三行乘以x 然后将第一行和第二行的结果除以第三行。



第37行: np.ravel将矩阵多维矩阵a (其中只有四个元素或两个元素)转化为一维矩阵,如果其中只有两个元素的话,进行如下操作

a = (0, 0, a[0], a[1])

然后将其转化为float类型的2*2的矩阵。



第43行: rect2rect_mtx(src, dst): 首先将传入的两个图像进行to_rect(a) 操作,然后(dst的第2行-第一行)/(src的第二行-第一行), 




common.py OpenCv例程阅读的更多相关文章

  1. video.py OpenCv例程阅读

    #!/usr/bin/env python ''' Video capture sample. Sample shows how VideoCapture class can be used to a ...

  2. camshift.py OpenCv例程阅读

    源码在这 #!/usr/bin/env python ''' Camshift tracker ================ This is a demo that shows mean-shif ...

  3. 【双目备课】OpenCV例程_stereo_calib.cpp解析

    stereo_calib是OpenCV官方代码中提供的最正统的双目demo,无论数据集还是代码都有很好实现. 一.代码效果: 相关的内容包括28张图片,1个xml和stereo_calib.cpp的代 ...

  4. OpenCV例程实现人脸检测

    前段时间看的OpenCV,其实有很多的例子程序,参考代码值得我们学习,对图像特征提取三大法宝:HOG特征,LBP特征,Haar特征有一定了解后. 对本文中的例子程序刚开始没有调通,今晚上调通了,试了试 ...

  5. python中 __init__.py的例程

    __init__.py一般是为空,用在一个python目录中,标识该目录是一个python的模块包 先上来看一个例子: .: test1 test2 test_init.py ./test1: tim ...

  6. OpenCV 例程

    采集图片显示视频: #include <iostream> #include <opencv2/opencv.hpp> using namespace std; using n ...

  7. Opencv Cookbook阅读笔记(四):用直方图统计像素

    灰度直方图的定义 灰度直方图是灰度级的函数,描述图像中该灰度级的像素个数(或该灰度级像素出现的频率):其横坐标是灰度级,纵坐标表示图像中该灰度级出现的个数(频率). #include <open ...

  8. 巡风源码阅读与分析---nascan.py

    Nascan是巡风主要是做目标的资产识别(信息收集). nascan.py 文件位于 nascan/nascan.py # coding:utf-8 # author:wolf@YSRC import ...

  9. python2.7-巡风源码阅读

    推荐个脚本示例网站:https://www.programcreek.com/python/example/404/thread.start_new_thread,里面可以搜索函数在代码中的写法,只有 ...

随机推荐

  1. 史上最全的CSS hack方式一览 jQuery 图片轮播的代码分离 JQuery中的动画 C#中Trim()、TrimStart()、TrimEnd()的用法 marquee 标签的使用详情 js鼠标事件 js添加遮罩层 页面上通过地址栏传值时出现乱码的两种解决方法 ref和out的区别在c#中 总结

    史上最全的CSS hack方式一览 2013年09月28日 15:57:08 阅读数:175473 做前端多年,虽然不是经常需要hack,但是我们经常会遇到各浏览器表现不一致的情况.基于此,某些情况我 ...

  2. ViewPagerIndicator

    https://github.com/eltld/ViewPagerIndicator

  3. IO管理与磁盘调度

  4. Creo二次开发--内存清理函数

    我们在处理模型文件时,总会遇到内存环境的清除问题.一个干净的Creo工作环境.是保证工作能顺利完毕的保障. ProMdlEraseNotDisplayed()函数提供了清除未显示模型的功能. 当须要循 ...

  5. 继承LinearLayout实现根据屏幕宽度及内部子View个数自动排布GridView

    public class VerticalSearchGridView extends LinearLayout implements View.OnClickListener { private i ...

  6. Spark 学习笔记:(四)MLlib基础

    MLlib:Machine Learning Library.主要内容包括: 数据类型 统计工具 summary statistics correlations stratified sampling ...

  7. JAVA学习之 Model2中的Servlet与.NET一般处理程序傻傻分不清楚

    时隔多日,多日合适吗,应该是时隔多月.我又想起了一般处理程序.这都是由于近期在实现的DRP系统中经经常使用到jsp+servlet达到界面与逻辑的分离.servlet负责处理从jsp传回的信息:每当这 ...

  8. JavaScript重点记忆

    String的常用方法 indexOf() 返回字符串中检索指定字符第一次出现的位置 lastIndexOf() 返回字符串中检索指定字符最后一次出现的位置 match() 找到一个或多个正则表达式的 ...

  9. C++使用模板、函数指针、接口和lambda表达式这四种方法做回调函数的区别比较

    在C++中,两个类之间存在一种关系,某个类需要另外一个类去完成某一个功能,完成了之后需要告知该类结果,这种最普通最常见的需求,往往使用回调函数来解决. 如题,我总结下来有这么四种方式可以完成这项功能, ...

  10. Hadoop 文件压缩

    一.目的 a. 减小磁盘占用 b. 加速网络IO 二.几个常用压缩算法 是否可切分:是指压缩后的文件能否支持在任意位置往后读取数据. 各种压缩格式特点: 压缩算法都需要权衡 空间/时间 :压缩率越高, ...