我擴大對Bessi的解決方案在這裏一點。我發現知道如何讓圖像佔據整個圖形並能夠嚴格控制輸出圖像大小非常有幫助。
% prevent the figure window from appearing at all
f = figure('visible','off');
% alternative way of hiding an existing figure
set(f, 'visible','off'); % can use the GCF function instead
% If you start getting odd error messages or blank images,
% add in a DRAWNOW call. Sometimes it helps fix rendering
% bugs, especially in long-running scripts on Linux.
%drawnow;
% optional: have the axes take up the whole figure
subplot('position', [0 0 1 1]);
% show the image and rectangle
im = imread('peppers.png');
imshow(im, 'border','tight');
rectangle('Position', [100, 100, 10, 10]);
% Save the image, controlling exactly the output
% image size (in this case, making it equal to
% the input's).
[H,W,D] = size(im);
dpi = 100;
set(f, 'paperposition', [0 0 W/dpi H/dpi]);
set(f, 'papersize', [W/dpi H/dpi]);
print(f, sprintf('-r%d',dpi), '-dtiff', 'image2.tif');
如果你想使圖到矩陣,鍵入「help @ AVIFILE/ADDFRAME」,然後提取稱爲「getFrameForFigure」子功能。這是一個Mathworks提供的函數,它使用一些(當前)未公開的從圖中提取數據的方式。