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.


to the question in the top, there is quite a simple solution provided by matlab:

% you so far

im = imread('image.tif');
imshow(im);
rectangle('Position', [100, 100, 10, 10]);

% now you use "getframe" and "frame2im"

f = getframe(gca);
im = frame2im(f);

imwrite(im,'image2.tif');

that worked great for me when i also drew a rectangle on an image and tried to save it. If you want to keep on working with it, just add

imread('image2.tif');

and keep on working with it :)

Regards, Laura