## Copyright (C) 2013  Ming Liu   <u5221472@gmail.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
function Irank = ranktf(image, window)
HWS = (window-1) / 2; %half window size
I = imread(image);
if size(I,3)~=1;
    I = rgb2gray(I);
end
[rows,cols] = size(I);
Irank = zeros(rows-window,cols-window); %the result image will be smaller
for a = 1+HWS : rows-HWS
    for b = 1+HWS : cols-HWS
        window = I(a-HWS:a+HWS , b-HWS:b+HWS);
        rankvector = sort(window(:)); %sort all pixels values in the window
        rank = find(rankvector == I(a,b)); %find the rank
        Irank(a-HWS,b-HWS) = rank(1);
    end
end
Irank = uint8(Irank);
end
%image is the real name of an image. windowsize is the size of window to
%be used for the rank transform, it must be an odd positive integer number
%greater than 3
%I is the rank transformed image, based on the window size you choose.
%For example, if the  window size is 3x3 and apply
%the window to the original grayscale image, then the center of the pixels
%within the window from the original grayscale image will be
%replaced by the ¡®rank¡¯ of the center pixel value. So it is between
%1 and 9, assuming there are no same pixel values. The advantage is all the
%pixel values in the image at last will be replaced by their ranks. So
%the noise and other mistakes during taking the photo will be ideally
%ignored. All the pixel values will be in a small range (the square of
%the window size). This is a very useful function in image processing