# Homomorphic filter classclassHomomorphicFilter:"""Homomorphic filter implemented with diferents filters and an option to an external filter.
High-frequency filters implemented:
butterworth
gaussian
Attributes:
a, b: Floats used on emphasis filter:
H = a + b*H
.
"""def__init__(self, a =0.5, b =1.5):
self.a =float(a)
self.b =float(b)# Filtersdef__butterworth_filter(self, I_shape, filter_params):
P = I_shape[0]/2
Q = I_shape[1]/2
U, V = np.meshgrid(range(I_shape[0]),range(I_shape[1]), sparse=False, indexing='ij')
Duv =(((U-P)**2+(V-Q)**2)).astype(float)
H =1/(1+(Duv/filter_params[0]**2)**filter_params[1])return(1- H)def__gaussian_filter(self, I_shape, filter_params):
P = I_shape[0]/2
Q = I_shape[1]/2
H = np.zeros(I_shape)
U, V = np.meshgrid(range(I_shape[0]),range(I_shape[1]), sparse=False, indexing='ij')
Duv =(((U-P)**2+(V-Q)**2)).astype(float)
H = np.exp((-Duv/(2*(filter_params[0])**2)))return(1- H)# Methodsdef__apply_filter(self, I, H):
H = np.fft.fftshift(H)
I_filtered =(self.a + self.b*H)*I
return I_filtered
deffilter(self, I, filter_params,filter='butterworth', H =None):"""
Method to apply homormophic filter on an image
Attributes:
I: Single channel image
filter_params: Parameters to be used on filters:
butterworth:
filter_params[0]: Cutoff frequency
filter_params[1]: Order of filter
gaussian:
filter_params[0]: Cutoff frequency
filter: Choose of the filter, options:
butterworth
gaussian
external
H: Used to pass external filter
"""# Validating imageiflen(I.shape)isnot2:raise Exception('Improper image')# Take the image to log domain and then to frequency domain
I_log = np.log1p(np.array(I, dtype="float"))
I_fft = np.fft.fft2(I_log)# Filtersiffilter=='butterworth':
H = self.__butterworth_filter(I_shape = I_fft.shape, filter_params = filter_params)eliffilter=='gaussian':
H = self.__gaussian_filter(I_shape = I_fft.shape, filter_params = filter_params)eliffilter=='external':print('external')iflen(H.shape)isnot2:raise Exception('Invalid external filter')else:raise Exception('Selected filter not implemented')# Apply filter on frequency domain then take the image back to spatial domain
I_fft_filt = self.__apply_filter(I = I_fft, H = H)
I_filt = np.fft.ifft2(I_fft_filt)
I = np.exp(np.real(I_filt))-1return np.uint8(I)# End of class HomomorphicFilter
img = cv2.imread('a1.jpg',0)
homo_filter = HomomorphicFilter(a =0.75, b =1.25)# a = 0.75, b = 1.25
img_filtered = homo_filter.filter(I=img, filter_params=[30,2])
cv2.imwrite('./output/a1_1.jpg', img_filtered)
# Homomorphic filter classclass HomomorphicFilter: """Homomorphic filter implemented with diferents filters and an option to an external filter. High-frequency filters implemented: butterworth gaussian Attributes: