Manual threshold_ What is wrong?

1 view (last 30 days)
Nisreen Sulayman
Nisreen Sulayman on 12 Sep 2019
Answered: DGM on 29 Apr 2023
img = imread('cameraman.tif');
%Threshold the image at the intensity level 128
%make all the values in the image less than 128 to 0 and equal or greater than 128 to 255
imgT = img;
[M N]=size(img);
for i=1:M
for j=1:N
if (img(i,j)==128 || img(i,j)>128)
imgT(i,j)=1;
else
imgT(i,j)=0;
end
end
end
figure;
subplot(1,2,1)
imshow(img)
subplot(1,2,2)
imshow(imgT, [])
imgT=uint8(imgT);

Answers (1)

DGM
DGM on 29 Apr 2023
This is another case of creating improperly-scaled images.
The incoming image img is uint8, and the output image imgT inherits its class from img. The loop sets output pixels to either 0 or 1, but in uint8, 0 is black and white is 255. The end result is a binarized image that's essentially black. Casting imgT to uint8 does nothing, because it's already uint8.
The code can be simplified.
% the image
inpict = imread('cameraman.tif');
% a binarized image of logical class
outpict = inpict >= 128;
% the output
imshow(outpict)
The result is a logical-class image that can directly be used for array indexing and other processing tasks. If the goal is to create a binarized image of uint8 class, then use im2uint8() to cast and scale the image properly for the output class.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!