How can I save a line plot as an image with specific pixel size?

Hello,
I am trying to create a program to compare images. One is a hand drawn image and the other is an original (see attached). I am able to plot the hand drawn image points using the following code but am not sure how to save it as a .png without axis labels/box and specify the axis lengths as the pixel dimensions (1024x768). I looked on the matlab website and it only gives directions on how to save image quality and size in inches. I need to save both plots as binary images so that they can be compared as below. Also I am hoping to export the images to another software to edit them.
How would I go about automatically saving the line plots as png 768x1025 pixels?
Here is my current code and it also loads the original image to show how they need to overlap for comparison.
%load drawing data
load('drawData.mat')
% plot picture (want it to be saved as 768/1024 px)
figure
plot(drawData(:,1),drawData(:,2),'-k',"linewidth",4)
xlim([0 768])
ylim([0 1024])
set(gca,'XTick',[], 'YTick', [])
% for example, load original image
y = imread("yoda.png");
[a b] = find(flipud(y(:,:,1) ==0));
%create plot of drawing and original image (need to eventually convert both
%to png from line graph to compare
figure
plot(drawData(:,1),drawData(:,2),'-k',"linewidth",4)
hold on
plot(b,a,'r.')
xlim([0 768])
ylim([0 1024])
set(gca,'XTick',[], 'YTick', [])
Thank you for your help!

 Accepted Answer

to save a matlab figure as a png image use the print function:
figure;
plot(x,y)
fig=gcf;
print(fig,'filename.png','-dpng')
you can configure things like resolution with Property-Value of this function

3 Comments

Thank you, I tried this and it works. However, the saved image width is 1167 and height is 875 eventhough the specifed axis heights in the code are 768 and 1024. Do you know why this change occurs and how the dimensions in pixels can be set when saving the image?
the print function adds a sort of margin to the picture, I don't know precisely how it does. what you can do is sizing your figure to what you want and then crop or resize the final image file:
fig=gcf;
fig.Position(3:4)=[1024 768];
print(fig,'filename.png','-dpng') % this will create a file that is actually 1600 by 1200
% when loading the file:
I=imread('filename.png');
% option 1: crop
win = centerCropWindow2d(size(I,1:2),[1024 768]);
I=imcrop(I,win);
% option 2: resizing
I=imresize(I,[1024 768]);

Sign in to comment.

More Answers (0)

Categories

Find more on Images in Help Center and File Exchange

Products

Release

R2021b

Asked:

FsC
on 8 Dec 2022

Commented:

FsC
on 12 Dec 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!