mark
1. 时域卷积等同于频域乘积
2. gauss blur卷积等同于热传导方程偏微分方程演化过程
import numpy as np
def fft_convolve(a,b):
n = len(a)+len(b)-1
N = 2**(int(np.log2(n))+1)
A = np.fft.fft(a, N)
B = np.fft.fft(b, N)
return np.fft.ifft(A*B)[:len(a)]
def fft_convolve2d(a,b,la, lb):
n = la + lb - 1
N = 2**(int(np.log2(n))+1)
A = np.fft.fft2(a, [N,N])
B = np.fft.fft2(b, [N,N])
shift = (lb-1)/2
return np.fft.ifft2(A*B)[shift:N-shift-1,shift:N-shift-1]
a = [x for x in range(1,6)]
b = [0.5 , 0.5]
c = np.convolve(a,b,mode='same')
print 'c=',c
print 'cf=', np.real(fft_convolve(a,b))
from scipy import signal as sg
from PIL import Image
def np_from_img(fname):
img = Image.open(fname)
img = img.convert('L')
return np.asarray(img, dtype=np.float32)
def save_as_img(arr, fname):
Image.fromarray(arr.round().astype(np.uint8)).save(fname)
def norm(arr):
return 255.0 * np.absolute(arr)/np.max(arr)
gauss_temp = [[1,2,1],[2,4,2],[1,2,1]]
gauss_temp = np.array(gauss_temp)
A = np.random.rand(5,5)
#print 'A=',A
conv = sg.convolve2d(A, gauss_temp, 'same')
print conv
print '########################'
convfft = fft_convolve2d(A,gauss_temp,5,3)
print np.real(convfft)
# img = np_from_img('e:/lena.jpg')
# print img.shape
# save_as_img(norm(sg.convolve(img, [[1.],
# [-1.]])),
# 'e:/lena-h.png')
# save_as_img(norm(sg.convolve(img, [[1., -1.]])),
# 'e:/lena-v.png')
# def common_size(a1, a2):
# """Chop-off the first rows and cols from the two numpy arrays a1
# and a2 so that they end up having the same size.
# >>> print common_size(np.array([[0, 0],
# ... [1, 2],
# ... [3, 4]]),
# ... np.array([[0, 5, 6],
# ... [0, 7, 8]]))
# (array([[1, 2],
# [3, 4]]), array([[5, 6],
# [7, 8]]))
# """
# (r1, c1) = a1.shape
# (r2, c2) = a2.shape
# return (a1[r1-r2 if r1>r2 else 0:,
# c1-c2 if c1>c2 else 0:],
# a2[r2-r1 if r2>r1 else 0::,
# c2-c1 if c2>c1 else 0:])
# def gradient(im):
# imv, imh = common_size(sg.convolve(im, [[1., -1.]]),
# sg.convolve(im, [[1.], [-1.]]))
# return np.sqrt(np.power(imv, 2)+np.power(imh, 2))
# img = gradient(img)
# print img.shape
# save_as_img(img,'e:/gr.png')
from scipy import misc
import matplotlib.pyplot as plt
lena = misc.lena()
#save_as_img(lena, 'e:/lena-gray.png')
gauss_temp = [[1, 4, 7, 4, 1],
[4, 16, 26, 16, 4],
[7, 26, 41, 26, 7],
[4, 16, 26, 16, 4],
[1, 4, 7, 4, 1] ]
lena_edge = sg.convolve2d(lena, gauss_temp, mode='same')
lena_edge = norm(lena_edge)
lena_edge = sg.convolve2d(lena_edge, gauss_temp, mode='same')
lena_edge = norm(lena_edge)
lena_edge = sg.convolve2d(lena_edge, gauss_temp, mode='same')
lena_edge = norm(lena_edge)
lena_edge = sg.convolve2d(lena_edge, gauss_temp, mode='same')
lena_edge = norm(lena_edge)
save_as_img(norm(lena_edge), 'e:/lena-edge.png')
参考
http://blog.jobbole.com/58246/
http://www.songho.ca/dsp/convolution/convolution.html
http://blog.sina.com.cn/s/blog_640029b301010xkv.html
<<图像处理的偏微分方程方法>>