Python 实现粒子滤波

 1 #
 2 # -*- coding=utf-8 -*-
 3 # 直接运行代码可以看到跟踪效果
 4 # 红色的小点代表粒子位置
 5 # 蓝色的大点表示跟踪的结果
 6 # 白色的方框表示要跟踪的目标
 7 # 看懂下面两个函数即可
 8 from numpy import *
 9 from numpy.random import *
10 
11 def resample(weights):
12     n = len(weights)
13     indices = []
14     # 求出离散累积密度函数(CDF)
15     C = [0.] + [sum(weights[:i+1]) for i in range(n)]
16     # 选定一个随机初始点
17     u0, j = random(), 0
18     for u in [(u0+i)/n for i in range(n)]: # u 线性增长到 1
19         while u > C[j]: # 碰到小粒子,跳过
20             j+=1
21         indices.append(j-1)  # 碰到大粒子,添加,u 增大,还有第二次被添加的可能
22     return indices # 返回大粒子的下标
23 
24 def particlefilter(sequence, pos, stepsize, n):
25     ''' sequence: 表示图片序列
26         pos: 第一帧目标位置
27         stepsize: 采样范围
28         n: 粒子数目
29         '''
30     seq = iter(sequence)
31     x = ones((n, 2), int) * pos      # 100   ``aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa~!aa个初始位置(中心)
32     f0 = seq.next()[tuple(pos)] * ones(n)  # 目标的颜色模型, 100 个 255
33     yield pos, x, ones(n)/n # 返回第一帧期望位置(expectation pos),粒子(x)和权重
34     for im in seq:
35         # 在上一帧的粒子周围撒点, 作为当前帧的粒子
36         x += uniform(-stepsize, stepsize, x.shape)#uniform()随机生成函数
37         # 去掉超出画面边框的粒子
38         x  = x.clip(zeros(2), array(im.shape)-1).astype(int)
39         f  = im[tuple(x.T)]  # 得到每个粒子的像素值
40         w  = 1./(1. + (f0-f)**2)  # 求与目标模型的差异, w 是与粒子一一对应的权重向量
41           # 可以看到像素值为 255 的权重最大(1.0)
42         w /= sum(w)      # 归一化 w
43         yield sum(x.T*w, axis=1), x, w # 返回目标期望位置,粒子和对应的权重
44         if 1./sum(w**2) < n/2.:    # 如果当前帧粒子退化:
45             x  = x[resample(w),:]  # 根据权重重采样, 有利于后续帧有效采样
46 
47 if __name__ == "__main__":
48     from pylab import *
49     from itertools import izip
50     import time
51     ion() # 打开交互模式
52     seq = [ im for im in zeros((20,240,320), int)]      # 创建 20 帧全 0 图片
53     x0 = array([120, 160])                              # 第一帧的框中心坐标
54 
55     # 为每张图片添加一个运动轨迹为 xs 的白色方块(像素值是255, 每帧横坐标加3,竖坐标加2)
56 
57     xs = vstack((arange(20)*3, arange(20)*2)).T + x0 # vstack: 竖直叠加
58     for t, x in enumerate(xs):   # t 从 0 开始, x 从 xs[0] 开始,enumerate 函数用于遍历序列中的元素以及它们的下标
59         # slice 的用法也很有意思,可以很方便用来表示被访问数组seq的下标范围
60         xslice = slice(x[0]-8, x[0]+8)
61         yslice = slice(x[1]-8, x[1]+8)
62         seq[t][xslice, yslice] = 255
63 
64     # 跟踪白框
65     for im, p in izip(seq, particlefilter(seq, x0, 8, 100)): #
66         pos, xs, ws = p
67         position_overlay = zeros_like(im)
68         position_overlay[tuple(pos)] = 1
69         particle_overlay = zeros_like(im)
70         particle_overlay[tuple(xs.T)] = 1
71         hold(True)
72         draw()
73         time.sleep(0.3)
74         clf()                                           # Causes flickering, but without the spy plots aren't overwritten
75         imshow(im,cmap=cm.gray)                         # Plot the image        spy(position_overlay, marker='.', color='b')    # Plot the expected position        spy(particle_overlay, marker=',', color='r')    # Plot the particles    show()
76  
posted @ 2016-05-21 15:53  阿夏z  阅读(1624)  评论(0编辑  收藏  举报