1

I have a code that loads an image to a plot, draws a rectangle on it an after this saves the image into a png file:

    figure('Visible', 'off');
    imshow(im)
    hold on
    for n=1:size(windowCandidates,1)
        rectangle('Position',[x,y,w,h],'EdgeColor','g','LineWidth',2)
    end
    f=getframe;
    [img_bound,map]=frame2im(f);
    imwrite(img_bound, strcat(directory, 'name.', 'png')); 
    hold off

How can I do the same without displaying it in a figure? Just modifying it and saving, I dont want the user to see all this process)

Thanks!

jsalvador
  • 733
  • 2
  • 7
  • 18
  • rectangles are easy enough to rasterize, so you should be able to modify the image matrix and draw on it directly, then save the result to disk. This avoid going through the process of screen-capture with functions like `GETFRAME`. You will probably find similar questions here on SO... – Amro Oct 29 '11 at 12:33
  • related question: [Render MATLAB figure in memory](http://stackoverflow.com/questions/4137628/render-matlab-figure-in-memory) – Amro Oct 26 '12 at 01:20

1 Answers1

2

You can make a figure invisible with:

figure('Visible', 'off');

And then just write it out as Matlab fig via:

saveas(gcf, 'path/to/filename');

or using the print command to png is this case

print('-dpng', 'path/to/filename');

Similar question with good answers and explanations else where on stackoverflow

Update

Thanks to Steve for pointing to this undocumented matlab function

function so;
close all;
im = imread('cameraman.tif');
hfig = figure('Visible', 'off'), imshow(im, 'Border', 'tight');
for n=1:2
rectangle('Position', [20*n, 20*n, 50, 50], 'EdgeColor', 'g', 'LineWidth', 2)
hold on;
end

F = im2frame(zbuffer_cdata(gcf));
imwrite(F.cdata, 'test.png'); 

%   Function copied from 
%   http://www.mathworks.com/support/solutions/en/data/1-3NMHJ5/?solution=1
%   -3NMHJ5
%
function cdata = zbuffer_cdata(hfig)
    % Get CDATA from hardcopy using zbuffer
    % Need to have PaperPositionMode be auto
    orig_mode = get(hfig, 'PaperPositionMode');
    set(hfig, 'PaperPositionMode', 'auto');
    cdata = hardcopy(hfig, '-Dzbuffer', '-r0');
    % Restore figure to original state
    set(hfig, 'PaperPositionMode', orig_mode);
Community
  • 1
  • 1
Maurits
  • 2,082
  • 3
  • 28
  • 32
  • I've tried it but didn't work. It keeps showing the images in increasing figures. I updated the code on the question. – jsalvador Oct 29 '11 at 10:42
  • The problem is with `getframe` . You can save a figure following the other stackoverflow example I linked through. – Maurits Oct 29 '11 at 11:38