MATLAB: How to find and replace extreme pixels in image for loop

pixels threshold

Hi, I have a set of the gray image dataset, and some of the images have extreme bright or dark pixels (e.g., for example, if I use imhist(fig), the histogram peak around the dark pixels from 0-10 or bright from 240-250) that I wish to replace values with. I'm wondering if there is a way to replace those extreme values to the specific pixel value (e.g. set threshold) either via the loop or on an individual image in order to recenter the histogram of images from the dataset. For example, I would like to replace pixel value from 0-10 by the values 11 and from 240-250 by the value 239. Here is my attempt that I am not sure how to improve/fix in order to reach the outcome. The outcome image I got is a blank white image, no error message. Any feedback or solution is appreciated. Thanks
image = im2double(imread('Face_23.jpg'));
image = image(:,:);
% allocate space for thresholded image
image_thresholded = zeros(size(image));
% loop over all rows and columns
for ii=1:size(image,1)
for jj=1:size(image,2)
% get pixel value
pixel=image(ii,jj);
% check pixel value and assign new value
if pixel<10
new_pixel=11;
elseif pixel>240
new_pixel=239;
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(image,[])
title('original image')
subplot(1,2,2)
imshow(image_thresholded,[])
title('thresholded image')

Best Answer

By the way: you define the folder, but do not use it. It is possible, that this is the only problem, although this is unlikely:
img_folder = '/Users/MATLAB/Faces';
img = im2double(imread(fullfile(img_folder, 'Face_23.jpg')));
More likely is, that after im2double the range of img is [0, 1], such that all pixel values are smaller than 10. Use im2uint8 instead, or the limits 10/255, or 240/255 respectively.
img = im2double(imread(fullfile(img_folder, 'Face_23.jpg')));
img(img < 10 / 255) = 11 / 255;
img(img > 240 / 255) = 239 / 255;
Another hint: "image" is a built-in Matlab functions. Avoid to use it as name of a variable, because this can cause confusions.
Do you see, that the method of "logical indexing" in img(img < 10 / 255) is much neater than the loop over the pixel indices?