Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save an altered image in MATLAB?

I want to read an image into MATLAB, draw a rectangle on it, and then save the image.

Also, I'm just learning MATLAB--please be gentle. It seems like it should be simple, but I can't seem to do it.

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

Even though I can see the rectangle on the image, the saved image does not display the rectangle. How can I save the image and have the rectangle show up?

FWIW, I've already tried saveas(), but that gives me a HUGE image. Is there a way to use saveas() and make the saved image the correct size?

like image 919
jacobko Avatar asked Feb 22 '09 19:02

jacobko


2 Answers

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.

like image 137
gnovice Avatar answered Nov 02 '22 21:11

gnovice


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

like image 41
Laura Avatar answered Nov 02 '22 21:11

Laura