Chris Gorman
Chris Gorman

Reputation: 195

Matlab create image from array and save without displaying

Apologies if this is a dupe, I've been searching for over an hour but the search terms are all really broad and I just keep getting the same results. Also I'm fairly new to matlab so apologies for any misunderstandings.

Anywho, I have a matlab program which needs to frequently save an image generated from a matrix, but I just can't figure out how to do that without displaying it first. Basically I'm caught in between two functions, image and imwrite, both only do half of what I want.

image is able to take my matrix and create the desired output, but it just displays it to a figure window

Output from <code>image</code> function

imwrite is able to save an image to a file without displaying it, but the image is completely wrong and I can't find any parameters that would fix it.

Output from <code>imwrite</code> function on same input

Other questions I've seen deal with using imread and managing figures and stuff, but I'm just doing (for example)

matrix = rand(20);
colormap(winter);
image(matrix, 'CDataMapping', 'scaled');

or

matrix = rand(20);
imwrite(matrix, winter(256), 'filename.png');

Is there some way to call the image function such that it doesn't display a figure window and then gets saved to a file? Something analogous to calling imshow and then savefig in matplotlib.

Upvotes: 0

Views: 565

Answers (1)

needarubberduck
needarubberduck

Reputation: 606

Just do this:

matrix = rand(20);
f = figure('visible', 'off');
colormap(winter);
image(matrix, 'CDataMapping', 'scaled');
print(f, '-dpng', 'filename.png');

Upvotes: 3

Related Questions