使用Python模拟高斯滤波过程并生成视频

Python在这类工作上的方便程度真的是——爽。

这里模拟的是低通高斯滤波的过程。

代码如下:需要numpy 和matplotlib,如果想保存成视频文件还需要下载ffmpeg

# encoding: utf-8
'''
Created on 2014年5月1日

@author: zcxsun
'''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
plt.rcParams['animation.ffmpeg_path'] = r'C:\sunxin\ffmpeg_x64\bin\ffmpeg.exe'

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()

speed = 1
size = 360
a = np.arange(size) *np.pi/180
b = np.zeros(size)
x = -0.1
for i in range(1,14,2):
    x = x*(i-2)/i
    b += x * np.sin(a*i)
b+= 0.02 * np.sin(a*50) + 0.01 * np.sin(a*150)
fix_signal = b

hamonic = 15

len = max(1, size/hamonic/2)
print len
scale = 0.3*len+0.8;
scale2x = -0.5/scale/scale
win =  np.exp( pow(np.arange(2*len+1)-len,2)*scale2x)
win/=sum(win)
move_gauss = win
print win.size
filtered_data = np.convolve(b, win, 'same')


#set the axis arrange
y_max = 0.4
ax = plt.axes(xlim=(0, 360), ylim=(-0.2, y_max))
line_gauss, = ax.plot([], [], lw=2)
line_filtered, = ax.plot([],[],lw=2)

plt.plot(fix_signal)

# initialization function: plot the background of each frame
def init():
    line_gauss.set_data([],[])
    line_filtered.set_data([],[])
    return line_gauss,line_filtered,
# animation function.  This is called sequentially
def animate(i):
    n = np.floor(i*speed)
    line_gauss.set_data(n+np.arange(0,win.size),win + (y_max-0.03-win.max()))
    line_filtered.set_data(np.arange(0,n),filtered_data[0:n])
    return line_gauss,line_filtered,
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=int(np.floor(size/speed)), interval=10, blit=True)

FFwriter = animation.FFMpegWriter(fps = 15)
path = r"C:\Users\Public\Documents\filter_show_hamonic_" + str(hamonic) + ".mp4"
anim.save(path, writer = FFwriter)
#
# plt.show()
print 'finish'

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注