Python Image理想的频域高/低通滤波器

时间:2015-11-06 16:38:25

标签: python image dns filtering frequency

我需要在频域实现Image Low / High pass文件管理器,以用于大学教育目的。 我正在应用的算法是:

a)对原始图像执行图像居中变换
b)执行DFT变换
c)根据所需的滤波来改变傅里叶系数 d)执行IDFT变换
e)再次执行图像居中变换(这取消了第一次居中变换)。

到目前为止,这是我的代码

import struct
import numpy as np
from math import pow
from cmath import exp, pi

imIn = open("before.bmp", "rb")

#Get informations from .bmp file section#
print 'Identifier: ', imIn.read(2)  
print 'File size: ', struct.unpack('i',imIn.read(4))[0]
print 'Reserved: ', struct.unpack('i', imIn.read(4))[0]
offset = struct.unpack('i', imIn.read(4))[0]
print 'Data offset: ',offset
print 'Header size: ',struct.unpack('i', imIn.read(4))[0]
width = struct.unpack('i', imIn.read(4))[0]
print 'Width: ',width
height = struct.unpack('i', imIn.read(4))[0]
print 'Height: ',height
#-------------------------------------------#


#back to zero and write header section which is copied from the original file
imIn.seek(0)
header = imIn.read(offset)
#----------------------------------------------------------------------------#


# build data array
imArr = []
count = 0
for i in range(0,width):
    row = []
    for j in range(0,height):
        tmp = imIn.read(1)
        val = struct.unpack('c', tmp)[0]
        row.append(val)
    imArr.append(row)
#------------------#


# write header information
imOut = open("after.bmp","wb")
imOut.write(header)
#-------------------------#
ArrInt =[]

for i in range(0,width):
    row = []
    for j in range(0,height):
        row.append(ord(imArr[i][j]))
    ArrInt.append(row)
del(imArr)

#center image
for i in range(0,width):
    row = []
    for j in range(0,height):
        ArrInt[i][j] = pow((-1),i*j)*ArrInt[i][j]
 #--------------------------------

#fourier transformation
iArr =  np.fft.fft2(ArrInt)
#---------------------------------------

#filer aplication(low pass filter)
R = 1000 #distance
for i in range(0,width):
    for j in range(0,height):
        temp = pow(float(height)/float(2)-i,2) + pow(float(width)/float(2)-j,2)
        if temp > pow(R,2):
            iArr[i][j] = 0
        elif temp <= pow(R,2):
            iArr[i][j] = iArr[i][j].real
#-----------------------------------

#fourier inverse transformation
iArr =  np.fft.ifft2(iArr)
#------------------------------

#center image
for i in range(0,width):
    row = []
    for j in range(0,height):
        iArr[i][j] = pow((-1),i*j)*iArr[i][j]
#---------------------------------------

for i in range(0,width):
    for j in range(0,height):
        if int(iArr[i][j].real) > 255:
            imOut.write(struct.pack('c',chr(int(255))))
        elif int(iArr[i][j].real) < 0:
            imOut.write(struct.pack('c',chr(int(0))))
        else: imOut.write(struct.pack('c',chr(int(iArr[i][j].real))))

#Close files section#
imIn.close()
imOut.close()
#-------------------#


我的问题是:我没有得到预期的结果,我无法弄清楚我做错了什么。 这些是我的输入和输出图像:
Input image
Output image

0 个答案:

没有答案
相关问题