Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions Image_Processing/src/Filters/src/gabor filter/frequest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 22 02:51:53 2016

@author: utkarsh
"""



# FREQEST - Estimate fingerprint ridge frequency within image block
#
# Function to estimate the fingerprint ridge frequency within a small block
# of a fingerprint image. This function is used by RIDGEFREQ
#
# Usage:
# freqim = freqest(im, orientim, windsze, minWaveLength, maxWaveLength)
#
# Arguments:
# im - Image block to be processed.
# orientim - Ridge orientation image of image block.
# windsze - Window length used to identify peaks. This should be
# an odd integer, say 3 or 5.
# minWaveLength, maxWaveLength - Minimum and maximum ridge
# wavelengths, in pixels, considered acceptable.
#
# Returns:
# freqim - An image block the same size as im with all values
# set to the estimated ridge spatial frequency. If a
# ridge frequency cannot be found, or cannot be found
# within the limits set by min and max Wavlength
# freqim is set to zeros.
#
# Suggested parameters for a 500dpi fingerprint image
# freqim = freqest(im,orientim, 5, 5, 15);
#
# See also: RIDGEFREQ, RIDGEORIENT, RIDGESEGMENT

### REFERENCES

# Peter Kovesi
# School of Computer Science & Software Engineering
# The University of Western Australia
# pk at csse uwa edu au
# http://www.csse.uwa.edu.au/~pk


import numpy as np
import math
import scipy.ndimage
#import cv2
def frequest(im,orientim,windsze,minWaveLength,maxWaveLength):
rows,cols = np.shape(im);

# Find mean orientation within the block. This is done by averaging the
# sines and cosines of the doubled angles before reconstructing the
# angle again. This avoids wraparound problems at the origin.


cosorient = np.mean(np.cos(2*orientim));
sinorient = np.mean(np.sin(2*orientim));
orient = math.atan2(sinorient,cosorient)/2;

# Rotate the image block so that the ridges are vertical

#ROT_mat = cv2.getRotationMatrix2D((cols/2,rows/2),orient/np.pi*180 + 90,1)
#rotim = cv2.warpAffine(im,ROT_mat,(cols,rows))
rotim = scipy.ndimage.rotate(im,orient/np.pi*180 + 90,axes=(1,0),reshape = False,order = 3,mode = 'nearest');

# Now crop the image so that the rotated image does not contain any
# invalid regions. This prevents the projection down the columns
# from being mucked up.

cropsze = int(np.fix(rows/np.sqrt(2)));
offset = int(np.fix((rows-cropsze)/2));
rotim = rotim[offset:offset+cropsze][:,offset:offset+cropsze];

# Sum down the columns to get a projection of the grey values down
# the ridges.

proj = np.sum(rotim,axis = 0);
dilation = scipy.ndimage.grey_dilation(proj, windsze,structure=np.ones(windsze));

temp = np.abs(dilation - proj);

peak_thresh = 2;

maxpts = (temp<peak_thresh) & (proj > np.mean(proj));
maxind = np.where(maxpts);

rows_maxind,cols_maxind = np.shape(maxind);

# Determine the spatial frequency of the ridges by divinding the
# distance between the 1st and last peaks by the (No of peaks-1). If no
# peaks are detected, or the wavelength is outside the allowed bounds,
# the frequency image is set to 0

if(cols_maxind<2):
freqim = np.zeros(im.shape);
else:
NoOfPeaks = cols_maxind;
waveLength = (maxind[0][cols_maxind-1] - maxind[0][0])/(NoOfPeaks - 1);
if waveLength>=minWaveLength and waveLength<=maxWaveLength:
freqim = 1/np.double(waveLength) * np.ones(im.shape);
else:
freqim = np.zeros(im.shape);

return(freqim);

59 changes: 59 additions & 0 deletions Image_Processing/src/Filters/src/gabor filter/gabor_enhancement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 18 11:42:58 2016

@author: utkarsh
"""

import numpy as np
#import cv2
#import numpy as np;
import matplotlib.pylab as plt;
import scipy.ndimage
import sys
import cv2

from image_enhance import image_enhance


if(len(sys.argv)<2):
print('loading sample image');
img_name = '01.jpg'
img = scipy.ndimage.imread('images/' + img_name);

elif(len(sys.argv) >= 2):
img_name = sys.argv[1];
img = scipy.ndimage.imread(sys.argv[1]);

if(len(img.shape)>2):
# img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img = np.dot(img[...,:3], [0.299, 0.587, 0.114]);


print(img.shape)

rows,cols = np.shape(img);
aspect_ratio = np.double(rows)/np.double(cols);

new_rows = 350; # randomly selected number
new_cols = new_rows/aspect_ratio;

#img = cv2.resize(img,(new_rows,new_cols));
img = scipy.misc.imresize(img,(np.int(new_rows),np.int(new_cols)));

enhanced_img = image_enhance(img);
enhanced_img = 255*np.uint8(enhanced_img)
kernel = np.ones((5,5),np.uint8)
# closing = cv2.morphologyEx(enhanced_img, cv2.MORPH_OPEN, kernel)
erosion = cv2.erode(enhanced_img,kernel,iterations = 1)

cv2.imshow('output',enhanced_img)
cv2.waitKey(0)



if(1):
print('saving the image')
scipy.misc.imsave('../enhanced/' + img_name, enhanced_img)
else:
plt.imshow(enhanced_img,cmap = 'Greys_r');
61 changes: 61 additions & 0 deletions Image_Processing/src/Filters/src/gabor filter/image_enhance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 18 22:50:30 2016

@author: utkarsh
"""
from ridge_segment import ridge_segment
from ridge_orient import ridge_orient
from ridge_freq import ridge_freq
from ridge_filter import ridge_filter
import cv2
import numpy as np
import scipy.ndimage

def image_enhance(img):
blksze = 40;
thresh=0.1
normim,mask = ridge_segment(img,blksze,thresh); # normalise the image and find a ROI
temp=normim -normim.min()
temp =temp/temp.max()
cv2.imshow("normim",normim)
cv2.waitKey(0)

gradientsigma = 1;
blocksigma = 9;
orientsmoothsigma = 7;
orientim = ridge_orient(normim, gradientsigma, blocksigma, orientsmoothsigma); # find orientation of every pixel
cv2.imshow("orientim",orientim)
cv2.waitKey(0)

blksze = 50;
windsze = 5;
minWaveLength = 5;
maxWaveLength = 15;
freq,medfreq = ridge_freq(normim, mask, orientim, blksze, windsze, minWaveLength,maxWaveLength); #find the overall frequency of ridges


freq = medfreq*mask;
kx = 0.65;ky = 0.65;
newim = ridge_filter(normim, orientim, freq, kx, ky); # create gabor filter and do the actual filtering
# temp=newim-newim.min();
# temp = temp/temp.max()
# cv2.imshow('output',newim)
# cv2.waitKey(0)


#gray = cv2.cvtColor(newim, cv2.COLOR_BGR2GRAY)
#thresholding
th, bin_im = cv2.threshold(np.uint8(newim),0,255,cv2.THRESH_BINARY);
# cv2.imshow('out',bin_im)
# cv2.waitKey(0)
# th3 = cv2.adaptiveThreshold((bin_im).astype('uint8'),255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)

# cv2.imshow('out',th3)
# kernel = np.ones((5,5),np.uint8)
# closing = cv2.morphologyEx(bin_im, cv2.MORPH_OPEN, kernel)
# cv2.imshow('outclosed',closing)
# cv2.waitKey(0)

cv2.waitKey(0)
return(newim<th )
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
145 changes: 145 additions & 0 deletions Image_Processing/src/Filters/src/gabor filter/ridge_filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 22 03:15:03 2016

@author: utkarsh
"""


# RIDGEFILTER - enhances fingerprint image via oriented filters
#
# Function to enhance fingerprint image via oriented filters
#
# Usage:
# newim = ridgefilter(im, orientim, freqim, kx, ky, showfilter)
#
# Arguments:
# im - Image to be processed.
# orientim - Ridge orientation image, obtained from RIDGEORIENT.
# freqim - Ridge frequency image, obtained from RIDGEFREQ.
# kx, ky - Scale factors specifying the filter sigma relative
# to the wavelength of the filter. This is done so
# that the shapes of the filters are invariant to the
# scale. kx controls the sigma in the x direction
# which is along the filter, and hence controls the
# bandwidth of the filter. ky controls the sigma
# across the filter and hence controls the
# orientational selectivity of the filter. A value of
# 0.5 for both kx and ky is a good starting point.
# showfilter - An optional flag 0/1. When set an image of the
# largest scale filter is displayed for inspection.
#
# Returns:
# newim - The enhanced image
#
# See also: RIDGEORIENT, RIDGEFREQ, RIDGESEGMENT

# Reference:
# Hong, L., Wan, Y., and Jain, A. K. Fingerprint image enhancement:
# Algorithm and performance evaluation. IEEE Transactions on Pattern
# Analysis and Machine Intelligence 20, 8 (1998), 777 789.

### REFERENCES

# Peter Kovesi
# School of Computer Science & Software Engineering
# The University of Western Australia
# pk at csse uwa edu au
# http://www.csse.uwa.edu.au/~pk



import numpy as np
import scipy;
def ridge_filter(im, orient, freq, kx, ky):
angleInc = 3;
im = np.double(im);
rows,cols = im.shape;
newim = np.zeros((rows,cols));

freq_1d = np.reshape(freq,(1,rows*cols));
ind = np.where(freq_1d>0);

ind = np.array(ind);
ind = ind[1,:];

# Round the array of frequencies to the nearest 0.01 to reduce the
# number of distinct frequencies we have to deal with.

non_zero_elems_in_freq = freq_1d[0][ind];
non_zero_elems_in_freq = np.double(np.round((non_zero_elems_in_freq*100)))/100;

unfreq = np.unique(non_zero_elems_in_freq);

# Generate filters corresponding to these distinct frequencies and
# orientations in 'angleInc' increments.

sigmax = 1/unfreq[0]*kx;
sigmay = 1/unfreq[0]*ky;

sze = np.round(3*np.max([sigmax,sigmay]));

x,y = np.meshgrid(np.linspace(-sze,sze,(2*sze + 1)),np.linspace(-sze,sze,(2*sze + 1)));

reffilter = np.exp(-(( (np.power(x,2))/(sigmax*sigmax) + (np.power(y,2))/(sigmay*sigmay)))) * np.cos(2*np.pi*unfreq[0]*x); # this is the original gabor filter

filt_rows, filt_cols = reffilter.shape;

gabor_filter = np.array(np.zeros((int(180/angleInc), (filt_rows), (filt_cols)), dtype = int))

angle_for_iter = (0,180/angleInc)
start_angle, last_angle = angle_for_iter
start_angle = int(start_angle)
last_angle = int(last_angle)
print(last_angle)
for o in range(start_angle,last_angle):

# Generate rotated versions of the filter. Note orientation
# image provides orientation *along* the ridges, hence +90
# degrees, and imrotate requires angles +ve anticlockwise, hence
# the minus sign.
rot_filt = scipy.ndimage.rotate(reffilter,-(o*angleInc + 90),reshape = False);
gabor_filter[o] = rot_filt;

# Find indices of matrix points greater than maxsze from the image
# boundary

maxsze = int(sze);

temp = freq>0;
validr,validc = np.where(temp)

temp1 = validr>maxsze;
temp2 = validr<rows - maxsze;
temp3 = validc>maxsze;
temp4 = validc<cols - maxsze;

final_temp = temp1 & temp2 & temp3 & temp4;

finalind = np.where(final_temp);

# Convert orientation matrix values from radians to an index value
# that corresponds to round(degrees/angleInc)

maxorientindex = np.round(180/angleInc);
orientindex = np.round(orient/np.pi*180/angleInc);

#do the filtering

for i in range(0,rows):
for j in range(0,cols):
if(orientindex[i][j] < 1):
orientindex[i][j] = orientindex[i][j] + maxorientindex;
if(orientindex[i][j] > maxorientindex):
orientindex[i][j] = orientindex[i][j] - maxorientindex;
finalind_rows,finalind_cols = np.shape(finalind);
sze = int(sze);
for k in range(0,finalind_cols):
r = validr[finalind[0][k]];
c = validc[finalind[0][k]];

img_block = im[r-sze:r+sze + 1][:,c-sze:c+sze + 1];

newim[r][c] = np.sum(img_block * gabor_filter[int(orientindex[r][c]) - 1]);

return(newim);
Loading