Python图像频域理想高/低通滤波器

2024-06-25 06:51:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要实现一个图像低通/高通滤波器在频域的教育目的在大学。 我使用的算法是:

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


Tags: inforreadrangewidthstructwriterow