tags:

views:

399

answers:

1

I'd like to show an image and plot something on it and then save it as an image with the same size as the original one. My MATLAB code is:

figH = figure('visible','off');
imshow(I);
hold on;
% plot something
saveas(figH,'1','jpg');
close(figH);

But the resulting image "1.jpg" has saved non-image areas in the plot as well as the image. How can I solve this problem?

+5  A: 

The reason your new image is bigger than your original is because the SAVEAS function saves the entire figure window, not just the contents of the axes (which is where your image is displayed).

Your question is very similar to another SO question, so I'll first point out the two primary options encompassed by those answers:

  • Modify the raw image data: Your image data is stored in variable I, so you can directly modify the image pixel values in I then save the modified image data using IMWRITE. The ways you can do this are described in my answer and LiorH's answer. This option will work best for simple modifications of the image (like adding a rectangle, as that question was concerned with).

  • Modify how the figure is saved: You can also modify how you save the figure so that it better matches the dimensions of your original image. The ways you can do this (using the PRINT and GETFRAME functions instead of SAVEAS) are described in the answers from Azim, jacobko, and SCFrench. This option is what you would want to do if you were overlaying the image with text labels, arrows, or other more involved plot objects.

Using the second option by saving the entire figure can be tricky. Specifically, you can lose image resolution if you were plotting a big image (say 1024-by-1024 pixels) in a small window (say 700-by-700 pixels). You would have to set the figure and axes properties to accommodate. Here's an example solution:

I = imread('peppers.png');      %# Load a sample image
imshow(I);                      %# Display it
[r,c,d] = size(I);              %# Get the image size
set(gca,'Units','normalized','Position',[0 0 1 1]);  %# Modify axes size
set(gcf,'Units','pixels','Position',[200 200 c r]);  %# Modify figure size
hold on;
plot(100,100,'r*');             %# Plot something over the image
f = getframe(gcf);              %# Capture the current window
imwrite(f.cdata,'image2.jpg');  %# Save the frame data

The output image image2.jpg should have a red asterisk on it and should have the same dimensions as the input image.

gnovice
Thanks, gnovice, I tried Azim's method. Nonimage area is gone but the saved image has different resolution than the original image. Can this be solved? Regards!
Tim
@Tim: I basically combined Azim's and SCFrench's suggestions and added a new solution to my answer above. Hopefully that will take care of things for you.
gnovice