octave saveas of custom-shape window to png saves only default window area - png

In octave 3.6.2 under windows 7, when I create a window with a particular shape (not the default)
figure ('Position', [0 0 800 500])
draw something, and then try to save the image:
saveas(gcf, 'test.png', 'png');
the result saves the default area of the window, not the area as currently defined.
If I try to set the paperposition:
set('paperposition', [.25 .25 18 4]);
The image shape does, in fact, change, but it is all background (white). The graph is still on the left side, not stretched out in the shape of the window.
How do I print a window in its current onscreen aspect ratio, or how to specify the size and shape of png I want?

If you want to output a png just
# plot your stuff
plot (rand (3, 3))
print ("myfile.png" ,"-S800,500")
-S specifies the size of the resulting PNG in pixels. "paperposition" and so on is important if you want to print to PDF where the papersize might be bigger than your plot. See "help print"

Related

Generate a checkerboard pattern of a particular size when printed

I was trying to generate a checkerboard pattern in MATLAB in such a way that when it is printed on a US letter sized paper, the width of each box will be 30 mm.
I tried to change various properties of gcf such as 'Units' and 'PaperSize' etc, but the PDF doesn't print as desired.
I came across several other online methods to generate what I need, but I would like to generate one in MATLAB. Any ideas? Below is sample code.
width = 30;
I = checkerboard(width,5,4);
I = I>0.5;
imshow(I);
saveas(gcf,'checkerboard.pdf')
Matlab can only generate the width based on pixel since Matlab doesn't know the physical dimensions of your screen.
One way is to find the Pixel Per Inch (PPI) of your screen. Here is a website to calculate the PPI by screen dimension and resolution. Then we can calculate the width (the pixel for 30mm) = PPI * 1.1811. (1.1811 inch is equal to 30 mm )
Example, for a screen of PPI = 220 (15.4 in, 2880 * 1800), width=220*1.1811=260.
There are figure properties that start with 'Paper' that specify the size and location of the figure on paper when printed (to PDF or to printer). Here is a list of all figure properties. You'll find these properties under the heading "Printing and Exporting" (see the table on contents on the left pane).
We can use these properties as follows. Note that we don't care about the size of the figure on the screen, so we leave it to the default size. What we do is set the 'PaperPosition' property so that the figure has a certain size when printed. We then create a drawing of a checkerboard pattern that fills the figure. The drawing will thus have the size of the figure itself when printed.
Note how we set the 'PaperSize' property in inches (8.5" x 11" is US Letter), but the 'PaperPosition' property in centimeters (so that we can easily figure out the 3x3 cm squares to draw).
The drawing itself could probably be simplified, but this works. It is much more efficient to draw the pattern using patches (i.e. create a vector drawing) than using an image (i.e. the checkerboard function in OP) when printing to PDF. The output is prettier and the file is smaller. But the same could be done displaying an image.
% Grid size (number of squares)
m = 6; n = 8;
% Square size (in centimeters)
side = 3;
% Create figure and set sizes for printing
figh = figure;
set(figh,'PaperUnits','inches','PaperSize',[8.5 11]);
set(figh,'PaperUnits','centimeters','PaperPosition',[1,1,side*m,side*n]);
% Create axes that fill the figure
axh = axes('Parent',figh,'Units','normalized','Position',[0,0,1,1]);
set(axh,'Color',[1,1,1])
set(axh.XAxis,'Visible','off');
set(axh.YAxis,'Visible','off');
% Draw rectangles
set(axh,'XLim',[0,m],'YLim',[0,n]);
for ii=0:m
for jj=0:n
if mod(ii+jj,2)==0
rectangle('Position',[ii,jj,1,1],'FaceColor',[0,0,0],'LineStyle','none');
end
end
end
% Print to PDF
print(figh,'-dpdf','checkerboard.pdf')

How can I keep Matlab figure window maximized when showing a new image?

I am programming a GUI in Matlab for an experiment where a test participant will view a series of images, and after each image, respond with a rating for the image.
I want to keep the window maximized at all times. An image will be displayed for a few seconds, then removed, some sliders will appear for the rating. Next, the sliders will be hidden, and a new image will appear, etc...
What I've got so far starts out fine with a maximized figure window, right until I load an image and display it, using imshow or image command, which causes the figure window to resize and fit to the image, instead of staying maximized. If I then maximize the figure window again, it causes a noticeable flicker from the window frame having first been maximized, then resized, then maximized again - a flicker I would like to avoid.
How can I keep the window maximized, and display an image at 1:1 ratio (NOT scaled or resized to fit the maximized window)?
I am aware of PsychToolbox, but it doesn't seem to have commands for creating sliders (which I would use for the rating), and I'd prefer not to have to do those from scratch.
I've also looked into windowAPI from Matlab File Exchange, but still haven't found a solution.
Below is an example of what I have now (using Matlab R2013a on Windows 7 64-bit):
screenSize = get(0,'screensize');
screenWidth = screenSize(3);
screenHeight = screenSize(4);
% Create figure window, keeping it invisible while adding UI controls, etc.
hFig = figure('Name','APP',...
'Numbertitle','off',...
'Position', [0 0 screenWidth screenHeight],...
'WindowStyle','modal',...
'Color',[0.5 0.5 0.5],...
'Toolbar','none',...
'Visible','off');
% Make the figure window visible
set(hFig,'Visible','on');
% Maximize the figure window, using WindowAPI
WindowAPI(hFig, 'Position', 'work');
% Pause (in the full version of this script, this would instead be
% a part where some UI elements are shown and later hidden...
pause(1.0);
% Read image file
img = imread('someImage.png');
% Create handle for imshow, and hiding the image for now.
% This is where Matlab decides to modify the figure window,
% so it fits the image rather than staying maximized.
hImshow = imshow(img);
set(hImshow,'Visible','off');
% Show the image
set(hImshow,'Visible','on');
Thanks,
Christian
Try the using the 'InitialMagnification' parameter with the 'fit' option value with imshow:
hImshow = imshow(img,'InitialMagnification','fit')
From this MathWorks tutorial:
You can also specify the text string 'fit' as the initial magnification value. In this case, imshow scales the image to fit the current size of the figure window
See also this section of the imshow docs regarding 'InitialMagnification'. So, that should keep your figure window the same size.
That would solve the issue of losing the window maximization.
To get an image displayed scaled at 1 pixel to 1 point on the screen, you can create an axis of the correct size for the image, and display into that:
fpos = get(hFig,'Position')
axOffset = (fpos(3:4)-[size(img,2) size(img,1)])/2;
ha = axes('Parent',hFig,'Units','pixels',...
'Position',[axOffset size(img,2) size(img,1)]);
hImshow = imshow(img,'Parent',ha);
Note that it is unnecessary to specify magnification since "If you specify the axes position (using subplot or axes), imshow ignores any initial magnification you might have specified and defaults to the 'fit' behavior", thus fitting to the axes specified by 'Parent'.

Matlab figure -> Word -> PDF results in bad quality

I create some figures with matlab and export them by using the "Edit -> Copy Figure" with setting "Preserve information (metafile if possible)". I import this in Word 2010. However, if I convert the word document with "save as pdf" the figures have artifacts.
The following image gives you an impression. To the left is Word at 400% zoom, to the right is the pdf with 400% zoom. One can clearly see that dotted lines become straight lines etc. How can I avoid this?
Expanding a bit on the answer that am304 gave - I just tested the following:
figure
% create a plot with some fine detail:
plot(sin(1./linspace(0.02, 1, 1000)));
% set the "paper size" of the figure (not the size on screen) to 30x20 cm:
set(gcf, 'PaperUnits', 'centimeters', 'PaperPosition', [0 0 30 20]);
% "print" to png with a resolution of 300 dpi
print('-dpng', 'myplot.png', '-r300');
This results in the following picture being saved to disk (cropped to show just detail):
The full size picture is just 43 kB - but it is a very high resolution (300 dpi) rendering so you can see the fine details of the plot.
I can insert this picture into a Word document and save it as a pdf. When I then take a screen shot of the pdf, it looks like this:
As you can see - the detail is pretty much all there.
You can use the print function to export your figure to various formats. EPS or TIFF should give good results. I wouldn't use the "Edit -> Copy Figure" if you want high quality figures.
I used the comments here to create my own approach (also with help of: How to set the plot in matlab to a specific size?). So here is my function:
function figureprint(hFig, width, height, res, filename)
%# figure size printed on paper
set(hFig, 'PaperUnits','centimeters')
set(hFig, 'PaperSize',[width height])
set(hFig, 'PaperPosition',[0 0 width height])
set(hFig, 'PaperOrientation','portrait')
%# export
print(hFig, '-dpng', res, filename)
This function is printing a figure to a specific size in cm. E.g.
figureprint(hFig, 12, 10, '-r1500', 'testPng.png')
So "hFig" is saved as a *.png with a width of 12cm and a height of 10cm. I measured this and this works fine. Optimizations are of course possible.
If you use
set(gca,'LooseInset', get(gca,'TightInset'))
the exponent of the multiply factor for the y values is cutted (when big numbers are plotted) (see image). In this cases you have to modify the values, e.g. like this:
tight = get(gca,'TightInset');
tight(1,4) = 0.08;
set(gca,'LooseInset',tight)

Export Matlab figure as PNG?

I need to automatically export figures from Matlab to PNG. My figure has a size of 600x200 px:
hFig = figure(1);
set(hFig, 'Color', [1 1 1]); % backgroundcolor white
set(hFig, 'Position', [500 500 600 200]) % size 600x200
I tried e.g.
print -dpng image.png
but the image.png is larger than 600x200 px. Exporting the figure manually from the Figure Window GUI using the "save" button works great, I want to do exactly this automatically / from a script. Thanks for any hint!
I also know the problem that figures save never look the same as on screen.
There is the saveas command which might work for you - but does also some resolution changing for me.
Only way I know is to carefully set every aspect like this:
set(gcf,'PaperUnits','inches','PaperSize',[2,6],'PaperPosition',[0 0 2 6])
print('-dpng','-r100','test')
(so paper size is 2x6" and print with 100dpi, PaperPosition is important as you will have otherwise some extra border.)
My preferred approach for generating png plots from MATLAB is the export_fig utility available at the MATLAB file exchange.
Here's an example:
set(gcf, 'Position', [100 100 500 500], 'Color', 'w')
x=0:0.01:10;
plot(x, sin(x))
set(gca, 'FontSize', 20, 'FontName', 'Arial')
export_fig 'strip-diff-far-forward.png' -painters -nocrop
This will create a png that is 500 x 500 pixels, with 20 pixel fonts. I'm sure that internally it does the same kinds of things as in bdecaf's answer, but it is all ecapsulated in a function for you already, and has a bunch of other features too.
The drawback is that if you use the -painters renderer (which I think looks the best) you will need to have ghostscript installed. If you don't want to mess with that, you can change -painters to -opengl
Edit Now setting figure size correctly!
Based upon bdecaf's answer:
set(gcf,'PaperUnits','inches','PaperSize',[600/96,200/96],'PaperPosition',[0 0 600/96 200/96])
print('-dpng','-r96','test')
96 is the dpi of my system. This gives me EXACTLY the same output as the save function. For Windows the dpi is typically 96, sometimes 120. Simply adjust it accordingly to your system. Note that on a beamer the DPI might again be different from your system, especially if your system has 120 DPI! 96 DPI should in general be a quite safe choice for beamers I think. Google if you need help finding out the DPI setting of your system. This answer is 99,9% based on bdecaf and Florian, so I will leave bdecaf's answer selected as the right one.
edit: 600 = horizontal image size in px, 200 = vertical image size in px
Amro answer works perfectly, after you generate your figure, set PaperPositionMode to auto and the print size will be the same as screen size.
set(gcf, 'PaperPositionMode','auto')
print('-dpng','test.png')
Try:
set(hFig, 'PaperPositionMode','auto') %# WYSIWYG
print -dpng -r0 image.png %# at screen resolution
This tells it to produce an image the same size as it appears on screen.

When saving a figure as eps file, Matlab cuts off colormap labels

I have a figure generated using contourf with a colorbar. Most of my plots are fine, but when the values on the colorbar are of the order 10^{-3}, either the numbers 0.005 etc are written by the colorbar, or x10^{-3} is written at the top.
In both cases, part of the label gets cut off - either the 3 in x10^{-3} or half of the 5 in 0.005.
I can fix this using
set(gca, 'ActivePositionProperty', 'OuterPosition')
for the figure onscreen, but I need to save it in eps format. When I do this, the 3 (or 5) is cut off again!
I can also fix this if I manually pull the bottom right corner of the figure window to make it larger. But this changes the sizes of the axis labels etc in comparison to the plot itself so that they're different to all my other figures, i.e. the figures that I don't resize.
Any suggestions?
Matlab uses two sizes for figures: screen size (Position figure property) and the PaperSize. The former is used for displaying on screen, and the latter for printing or exporting to image formats other than .fig. I suspect this is the source of your problem.
Here is what you can try:
size = get(gcf,'Position');
size = size(3:4); % the last two elements are width and height of the figure
set(gcf,'PaperUnit','points'); % unit for the property PaperSize
set(gcf,'PaperSize',size);
This sets the size of the "paper" to export to .eps to the size of the figure displayed on screen.
If this doesn't work, you can try to play a bit with PaperSize or other "paper" related properties. The Figure Properties documentation page gives more info about properties.
Hope this helps!
The former suggestion is partly correct. Here is what i did:
set both, figure and paper units, to the same measure (figure has pixels, not points!)
set(gcf,'Units','points')
set(gcf,'PaperUnits','points')
do the same as suggested before:
size = get(gcf,'Position');
size = size(3:4);
set(gcf,'PaperSize',size)
the thing now is, that it might be shifted off the paper, as in my case, so put it back on
set(gcf,'PaperPosition',[0,0,size(1),size(2)])
I am not sure about the offset of [0,0], but what is a single point cut off :)
Try this to save your file to filename.eps:
set(gcf,'Units','points')
set(gcf,'PaperUnits','points')
size = get(gcf,'Position');
size = size(3:4);
set(gcf,'PaperSize',size)
set(gcf,'PaperPosition',[0,0,size(1),size(2)])
print(gcf,'filename','-depsc','-loose'); % Save figure as .eps file