-1

I am trying to make a dynamic thresholding, but It is appearing some errors. I am trying to adapt from this code: http://www.inf.ed.ac.uk/teaching/courses/ivr/lectures/ivr5hand.pdf

function [Output ] = dinamicthresh()

[filename,pathname] = uigetfile('*.bmp; *.jpg', 'Please select an image file');     


I=fullfile (pathname,filename); 


I=imread(I);


I=rgb2gray(I);


I=im2double(I);

[H,W]= size(I);
Output= zeros(H,W);

halfH=round(H/2);
halfW=round(W/2);

for i= H:H
for j = W:W
    C = I(i-halfH:i+halfH,j-halfW:j+halfW);
    adaptative_thresh = mean(mean(C)) - 12;
          if I(i,j) < adaptative_thresh 
        Output(i,j)= 1;
            else 
        Output(i,j)= 0;
    end
end
end

subplot(1,2,1);imshow(I);title('Original Image');
subplot(1,2,2);imshow(Output);title('Adaptive Thresholding');

end
madebydavid
  • 6,457
  • 2
  • 21
  • 29
  • 1
    Could you please provide some informat about the errors you're receiving and what part of the code is giving you the errors? – Alex A. Mar 03 '15 at 17:40
  • Your `for` loops have ranges of `H:H` and `W:W`... each one is executed once. That looks suspect. I would expect something like `1:H` and `1:W`. – beaker Mar 03 '15 at 18:20

1 Answers1

0

Your thresholding algorithm compares the difference between each pixel and the local average to a given threshold.

This task can be performed in a much more straightforward manner in Matlab, using filter2.

For instance with this image:

enter image description here

% --- Parameters
w = 20;
h = 20;
th = 12;

% --- Load image
Img = double(rgb2gray(imread('Img.png')));

% --- Get the locally-averaged image
Mean = filter2(fspecial('average', [h w]), Img);

% --- Get thresholded image
BW = (Img-Mean)>th;

% --- Disply result
imshow(BW)

I obtain the following result:

enter image description here

Of course, you can play around with the parameters to adapt this code to your images:

  • w is the width of the averaging box
  • h is the height of the averaging box
  • th is the threshold for the difference with the mean.

Best,

Ratbert
  • 5,463
  • 2
  • 18
  • 37