function image_new = bandpass_imfilt(image, d1, d2, n)

% This function filters an image with a Butterworth bandpass filter
%
% Input:
% image: name of a NxM matrix representing an image (any image can be read 
% into this matrix using matlab's function "imread". The image
% must be rescaled to grayscale with matlab's "rgb2gray" function).
%
% d1, d2 - frequency limits of the bandpass filter, given in cycles per image
% n - filter's order
% 
% output:
% filtered image
% 
% Olga Dyakova, Motion Vision Group, Uppsala University, 2015

fft_image = fftshift(fft2(image));
[x,y] = size(image);
freq1=-x/2:x/2-1;
freq2=-y/2:y/2-1;
[x1,y1]=meshgrid(freq2,freq1);
[~, ro]=cart2pol(x1,y1);
ro1=round(ro);

filter=zeros(x,y);

for r1=0:x-1   
    idx= ro1==r1;    
    temp = (1/(1 + (r1/d2)^(2*n))).*(1-1/(1 + (r1/d1)^(2*n)));    
    filter(idx)=temp;
end

imagefilt=fft_image.*filter;

filter_image_shiftback=ifftshift(imagefilt);
image_new=(real(((ifft2(filter_image_shiftback)))));
image_new=uint8(((image_new-min(image_new(:)))./((max(image_new(:)))-min(image_new(:)))).*255);
figure
imshow(image_new);