MATLAB: Changing values of pixels in an image pixel by pixel (image in .jpeg format)

a

Hi everyone, I'm trying to replace all pixels with value 255 (on a grayscale image) to 249 without changing other grayscale values. The image is in .jpeg format and I would like to obtain image after changes back in jpeg format. Thanks for helping me in advance. regards

Best Answer

im = imread('yourimage.jpg');
im(im == 255) = 249; %assume the image is indeed greyscale. No guarantee with jpg
imwrite(im, 'newimage.jpg');
Note that since you care about intensity values, using jpeg is not a good idea. jpeg is a lossy compression format. The pixel values stored in the file may be slightly different from the original one. Each time you save to jpg, you worsen the problem.
Also note that jpg does not know about grayscale images. The image will always be saved as RGB (with all three channels equal, but the compression may add colour)
Use png instead which can save true grayscale and has non-lossy compression.