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:
my_image = im2double(imread('picture.tif'));
my_image = my_image(:,:,1);
image_thresholded = my_image;
image_thresholded(my_image>3) = 256;
image_thresholded(my_image<0.5) = 0;
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:
my_image = im2double(imread('picture.tif'));
my_image = my_image(:,:,1);
image_thresholded = zeros(size(my_image));
for ii=1:size(my_image,1)
for jj=1:size(my_image,2)
pixel=my_image(ii,jj);
if pixel<0.5
new_pixel=0;
elseif pixel>3
new_pixel=256;
else
new_pixel = pixel;
end
image_thresholded(ii,jj)=new_pixel;
end
end
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?
Best Answer