How can I save an altered image in MATLAB?

The reason the rectangle doesn’t show up in the saved image is because you are not modifying the variable im, which stores the image data. The rectangle is simply a plot object displayed over the plotted image. You have to modify the image data itself.

Typically, images read into MATLAB are loaded as an N-by-M-by-3 matrix (i.e. an N-by-M pixel image with RGB (red-green-blue) values for each pixel). Usually, the image data is a uint8 data type, so the RGB values range from 0 to 255. If you wanted to change the RGB value for a given pixel, you would do the following:

im = imread('test.jpg');  % Load a jpeg image
im(1,1,1) = 255;  % Change the red value for the first pixel
im(1,1,2) = 0;    % Change the green value for the first pixel
im(1,1,3) = 0;    % Change the blue value for the first pixel
imwrite(im,'new.jpeg');  % Save modified image

There are different ways you can modify more than one pixel at a time (i.e. a rectangular area), which will require that you look into how to index into multidimensional arrays. For more detail about how different types of images are read into MATLAB (i.e. truecolor vs. indexed), I would check the documentation for imread.

Leave a Comment