MATLAB: Changing values of pixels in an image pixel by pixel ( Thresholding )

changing pixel valuesImage Processing Toolboxthresholding

Hi everyone, I'm trying to put a threshold on a grayscale image, and I'm doing it this way: that a "for" loop reads the image pixel by pixel, and if the value of the pixel is less than "0.5" sets its' value to "0", and if it is more than "3", sets it to "256". Here it is my code:
my_image =imread('picture.tif');
for R=1:num of Rows
for C=1:num of Columns
pixel=my_image(R,C);
if pixel<0.50000000 , pixel=0.000000000;, end
if pixel>3.00000000 , pixel=256;, end
thresh(R,C)=pixel;
end
end
im_thresh=mat2gray(thresh);
figure,imshow(im_thresh);
title('thresholding');
But it doesn't work properly. Sometimes it misses some values that ought to be changed, and sometimes changes the ones that shouldn't be changed, to arbitrary values…for example changes the value "0.8182" to "0.0032". It also doesn't have enough accuracy, for example instead of changing the value "0.425" to "0", changes it to "0.0002". Could you please tell me what's causing this problem, and help me to fix the code?! Thanks in advance…

Best Answer

First of all, it is not necessary to loop over all pixels individually. You can simply use operations on your image matrix, which would look like this:
% read in tiff image and convert it to double format

my_image = im2double(imread('picture.tif'));
my_image = my_image(:,:,1);
% perform thresholding by logical indexing
image_thresholded = my_image;
image_thresholded(my_image>3) = 256;
image_thresholded(my_image<0.5) = 0;
% display result

figure()
subplot(1,2,1)
imshow(my_image,[])
title('original image')
subplot(1,2,2)
imshow(image_thresholded,[])
title('thresholded image')
The line image_thresholded(my_image>3) = 256; is an example of logical indexing, it will assign the value 256 to all matrix elements in image_thresholded for which the same matrix element in my_image is larger than 3.
If you prefer looping over all pixels (which is not advisable due to its slow speed), your code should look something like this:
% read in tiff image and convert it to double format
my_image = im2double(imread('picture.tif'));
my_image = my_image(:,:,1);
% allocate space for thresholded image
image_thresholded = zeros(size(my_image));
% loop over all rows and columns
for ii=1:size(my_image,1)
for jj=1:size(my_image,2)
% get pixel value
pixel=my_image(ii,jj);
% check pixel value and assign new value
if pixel<0.5
new_pixel=0;
elseif pixel>3
new_pixel=256;
else
new_pixel = pixel;
end
% save new pixel value in thresholded image
image_thresholded(ii,jj)=new_pixel;
end
end
% display result
figure()
subplot(1,2,1)
imshow(my_image,[])
title('original image')
subplot(1,2,2)
imshow(image_thresholded,[])
title('thresholded image')
Does this help you out?