Use imagesc(bw)
(instead of image(bw)
). That automatically scales the image range.
Also, note that you can replace all your code by this vectorized, more efficient version:
bw = double(I>mean(I(:)));
Domanda
I have to write a program that converts intensity images into black-and-white ones. I just figured I could take a value from the original matrix, I, and if it's above the mean value, make the corresponding cell in another array equal to 1, otherwise equal to zero:
for x=1:X
for y=1:Y
if I(x,y)>mean(I(:))
bw(x,y)=1;
elseif I(x,y)<mean(I(:))
bw(x,y)=0;
end
end
end
image(bw)
Unfortunately, the image I get is all black. Why?
I is in uint8
, btw. 2-D Lena.tiff image
Soluzione 2
Use imagesc(bw)
(instead of image(bw)
). That automatically scales the image range.
Also, note that you can replace all your code by this vectorized, more efficient version:
bw = double(I>mean(I(:)));
Altri suggerimenti
Use this :
bw = im2bw(I, graythresh(I));
Here the documentation for im2bw;
using imshow(I,[]);
, doesn't evaluate the image between 0 and 255, but between min(I(:))
and max(I(:))
EDIT
You can change graythresh(I)
by anyother level. You can still use the mean of your image. (Normalize between 0 and 1).
maxI = max(I(:));
minI = min(I(:));
bw = im2bw(I,(maxI - mean(I(:)))/(maxI - minI));
One problem is that you are always using the mean
untill then.
What you will want to do is do this before the loop:
myMean = mean(I(:));
And then replace all following occurences of mean(I(:))
by myMean
.
Using the running mean as you currently will definitely slow things, but it will not be the reason why it becomes all black.