Reputation:
İn Matlab, I want to threshold a grayscale image to convert it to a black & white image:
for k=1:Y
for i=1:X
if gray(i,k)>T
gray(i,k)=1;
else
gray(i,k)=0;
end
end
end
What do you think should be the value of T?
Upvotes: 1
Views: 17304
Reputation: 1439
Dusty's answer of using Otsu's method is built-in in MATLAB.
The following code is from the MATLAB page about the graythresh function (which implements Otsu's method).
I = imread('coins.png');
level = graythresh(I);
BW = im2bw(I,level);
imshow(BW)
Upvotes: 0
Reputation: 9621
Inbuilt function im2bw takes level as one of the parameters. So instead of using for loops we can use it for conversion. Default level is 0.5.
From: http://www.mathworks.com/help/images/ref/im2bw.html
im2bw
Convert image to binary image, based on threshold
Syntax
BW = im2bw(I, level)
BW = im2bw(X, map, level)
BW = im2bw(RGB, level)
Upvotes: 0
Reputation: 16035
If I were you, I would use the median:
gray=double(gray>median(gray(:)))
PS: you should use this more efficient code in general:
gray=double(gray>T)
Upvotes: 5