1

I am trying to write a function that thresholds a grey-level image F and a threshold value t (0 ≤ t ≤ 255) such that r = 0 for r < t and r = 255 otherwise.

I have tried to implement this, but imshow(r) does not produce an output.

function f = imgThreshold(img, t)

f = img;

if (f < t)
    f = 0;
else
    f = 1;
end

img = imread('https://i.stack.imgur.com/kP0u2.png');
t = 20; 
r = imgThreshold(img, t);
imshow(r); 

This should threshold this image. However, it does not do so. What am I doing wrong?

Adriaan
  • 17,741
  • 7
  • 42
  • 75

1 Answers1

3

Best would be to use logical indexing:

f(f<t)=0; % set all elements of f<t to 0
f(~(f==0))=1; % Set all elements where f is not 0 (i.e. the rest) to 1

f<t nicely produces a logical matrix adhering to the condition, but subsequently you do either f=1 or f=0, meaning that you set the entirety of f to be a scalar (one or zero), which of course just plots a black or white square. Instead, use the logical matrix as indexing operation into the matrix itself, then assigning the desired value to each true entry, like above.

Also a function definition either goes in its own file, or on the bottom of the script. Thus either you save the function as imgThreshold.m and leave the rest for the script, or first call the script and place function f = imgThreshold(img, t) etc after the call to imshow

Adriaan
  • 17,741
  • 7
  • 42
  • 75