Matlab in Linux: fontsize different between eps and fig export - matlab

I wish to export figures both in eps and tiff (or png) using Matlab. Following this thread, I can change figure size and resolution conveniently. But now my problem is that the font sizes in my exported eps and tif files are very different.
For example:
1: using 300 dpi resolution to save a tif file:
r=300;
set(gcf, 'PaperUnits', 'inches', 'PaperPosition', [0 0 1024*2 1024*2]/r)
print(gcf,'-dtiff',sprintf('-r%d',r), 'contour.tif');
I get a very small font size (same applies when saving to png and jpg)
Perhaps the resolution is affecting the font size. Because when I set r=0 (i.e. resolution the same as the display), the font size is very close to what I want:
r=300;
set(gcf, 'PaperUnits', 'inches', 'PaperPosition', [0 0 1024*2 1024*2]/r)
print(gcf,'-dtiff',sprintf('-r%d',0), 'contour.tif');
But the problem is that such resolutions can not be published as zigzags. This can be seen when slightly zoomed in.
Just wondering how I can set all figure outputs to be consistent between formats, particularly between eps and tiffs, without using third party software (e.g. using Illustrator to export)?

I found this problem is associated with the missing font in linux. I use the following commands to resolve three machines installing different distros:
for a ubuntu machine, run:
sudo apt-get install xfonts-75dpi xfonts-100dpi
for a gentoo machine, run:
emerge -av media-fonts/font-adobe-100dpi media-fonts/font-adobe-75dpi liberation-fonts
for a centos machine, run:
yum install xorg-x11-fonts-75dpi xorg-x11-fonts-100dpi
I have to reboot the computer to make the configuration in effect.

Related

How to prevent that print changes image resolution?

I tries to create a text image (i think it is called that way) in matlab. That means that I want to create an image containing text. The problem is that there is no matlab function that can do this. The solution is that I use text and then captures the output in the figure.
In the beginning I used getframe to capture the output. This went completely fine as long as I did not do anything else on the screen at the same time. The problem is that |getframe| captures whatever is on the screen at the moment, which have led to annoying bugs. In hope of solving this problem I plan to use |print| instead. However, now I have the problem of image resolution changes when print is used. Do anyone know a solution for this?
This is what I have tried so far:
xlen = 1200; ylen = 700;
im = uint8(255*ones(ylen,xlen,3));
hf = figure('color','white','units','normalized','position',[.1 .1 .8 .8]);
image(ones(size(im)));
set(gca,'units','pixels','position',[5 5 size(im,2)-1 size(im,1)-1],'visible','off')
text('units','pixels','position',[1 ylen/2],'fontsize',60,'FontWeight','Bold','string','This is text')
set(hf,'Units','pixels')
set(hf,'Position',[100,100,xlen,ylen],'paperpositionmode','auto');
print(hf, '-dpng', 'myText.png');
Saving images in matlab can be a real struggle.
I found my solution by using export_fig from the mathlab file exchange (see
http://www.mathworks.com/matlabcentral/fileexchange/23629-export-fig).
Some of the aims of export fig are:
Figure/axes reproduced as it appears on screen
Cropped borders (optional)
Embedded fonts (pdf only)
Ok I have finally found a solution. Matlab uses 150 dpi resolution by default. This is kind of weird since windows use 96 dpi resolution in their operating system and mac uses 72 dpi. However, what I have heard it is recommended to use at least 150 dpi on printed material to get good quality. Anyway, since windows uses 96 dpi, it is clear that you need to set the image resolution to 96 dpi as well to print (refering to matlabs function print) a figure with the right size.
xlen = 1200; ylen = 700;
im = uint8(255*ones(ylen,xlen,3));
hf = figure('color','white','units','normalized','position',[.1 .1 .8 .8]);
image(ones(size(im)));
set(gca,'units','pixels','position',[5 5 size(im,2)-1 size(im,1)-1],'visible','off')
text('units','pixels','position',[1 ylen/2],'fontsize',60,'FontWeight','Bold','string','This is text')
set(hf,'Units','pixels')
set(hf,'Position',[100,100,xlen,ylen],'paperpositionmode','auto');
print(hf, '-dpng', '-r96','myText.png'); % SET RESOLUTION TO '-r96' for windows.

How to set the font settings in .pdf, publish via MATLAB and LATEX

While trying to publish a .pdf file for .m MATLAB code, equations (written in latex) are not properly rendered in appropriate (smooth) font, instead fonts looks scattered.
I did try to fix the problem by decreasing the font-size of the editor but that didn't work.
For example: the MATLAB code is:
%% (a) From above plot there are no signs of convergence of $\rho$
%%
% $x^2+e^{\pi i}$
then the .pdf file is not well written, in which equation's fonts are not smooth enough.
thanks for any suggestions.
I was having the same problem, with equation rendering quality being inadequate.
This is my procedure for fixing this in MATLAB R2013b.
1) In the MATLAB command prompt, enter:
edit publish
This should pop up the editor for you to edit 'publish.m'. Beware, the file may be read only. Under Linux, I use an external editor as superuser to edit it.
2) Go to line 811. You should see this:
temptext = text('Parent',tempaxes,'Position',[.5 .5], ...
'HorizontalAlignment','center','FontSize',22, ...
'Interpreter','latex');
Change the value of 'Fontsize' to something larger; I used 30.
3) Go to line 747. You should see this:
swapTexForImg(dom,equationNode,outputDir,fullFilename,equationText,newSize(2),newSize(1))
Change that to
swapTexForImg(dom,equationNode,outputDir,fullFilename,equationText,newSize(2)/scale,newSize(1)/scale)
where scale is the scale factor of your liking. Might have to play with it a bit until you get it right; I used 2.
4) Save the file. Also keep a backup of the original.
5) In the MATLAB command prompt, enter:
rehash toolboxcache
followed by:
clear functions
6) Run publish again.
This should do the job for the PDF. I haven't tried it for HTML, but it should also work. In case of HTMl, don't forget to delete the images created previously.

How to convert image to EPS file without leaving any margins with MATLAB?

I am converting images to EPS files with the following script.
%% Image 2 eps file.
% - img: the image.
% - eps: eps filename.
function Image2Eps(img, eps)
imshow(img,'border','tight','InitialMagnification',100);
print(gcf,'-depsc',eps);
end
The file generated almost bound the image tightly.
But a small margin is always left on the top and on the right side.
How to make the EPS file exactly the size of the bitmap image?
If you are not too locked on Matlab. You can use Image Magick to do the conversion.
I used it in a command line:
imgtops2.exe imge.ppm -e -c 0,0 -o image.eps
I used it on a Windows machine, but I believe they have working binaries for other OS as well.
Furthermore, once you have a working command line in dos or shell you can call it from Matlab using system, dos or unix commands.
PS.
I used an old version of ImageMagick, in more recent releases they might have changed imgtops2 to convert, you'll have to look at their documentation.

Saving MATLAB figures as PDF with quality 300 DPI, centered

I want to save a MATLAB figure as PDF, with quality 300 DPI, and centered.
So far I managed to save it, but the image appears cropped. I changed the page type to A3 and kind of solves the problem, but I am looking for something more elegant. I am doing it from the GUI, but maybe from the command line is easier in MATLAB.
Is there any package or script that makes this (fundamental task for publications and papers) a bit easier?
Try using the following command:
print -painters -dpdf -r300 test.pdf
You will, of course, already have to have a file named test.pdf in the current directory.
Some notes on the -commands as well.
-painters: this specifies the use of the painters alogrithm for the exporting.
-dpdf: specifies a vector image, specially a pdf in this case. This is through Ghostscript.
-r300: specifies a 300 dpi resolution. -r400 would be 400 dpi and so on.
On an off note. I tend to just save the figure as a high DPI tiff image and import that tiff into another program where I actually assemble my figure(s) for the paper. I tend to lean towards CorelDraw personally.
I would recommend to check the exportfig package
exportfig(gcf, path_to_file, 'format','pdf','Resolution', 300 )
also, you can check fig package, which is nice to call before the exportfig:
figure
plot(x,y)
fig
exportfig(gcf, path_to_file, 'format','pdf','Resolution', 300 )

How to export non-blurry eps images?

I'm exporting an image in Matlab using the eps format, but it smooths the image. Matlab does not blur the image using other formats such as png. I would like to know how to export a non-blurry image with eps format. Here is the resulting image using png:
And here is the resulting image using eps:
UPDATE:
The problem is reproducible on a Mac, and the issue is with the eps renderer rather than MATLAB. For e.g., saving imagesc(rand(20)) and viewing with Preview and GSview results in the following:
Preview screenshot
GSview screenshot
Clearly, the information is not lost. It is just not interpreted/read correctly by some EPS viewers. The solution is simple: use GSview to view your eps images. You can download it from here
On Macs especially, if your end application is latex/pdflatex, you will have to explicitly set it to use GS/GSview, because otherwise, it will default to the Quartz engine, which is baked into the OS.
PREVIOUS ANSWER:
I am unable to reproduce the behavior your described. Here is the code I used, tested using R2010b on WinXP 32-bit:
M = fspecial('gaussian',[20 20],5);
imagesc(M)
print('-dpng','a.png')
print('-depsc2','b.eps')
a.png
b.eps
Perhaps this is an issue with your EPS viewer...
not sure why it works but you can try doing the following:
eps2eps oldfile newfile
does the trick for me (on a mac os)
At first I thought you were doing something incorrectly, but then I remembered that this was an issue that was bothering the hell out of me a year or so ago. I couldn't come up with a way to "fix" this behaviour and from what I've researched, this is most likely a bug and several others have had this problem too and there is no known solution. Of course, I could be wrong about the last part and there might be solutions out there that have come out since I looked for them.
Any way, my workaround this problem was to use pcolor with shading flat instead of imagesc. When you export this to an eps format it preserves the image correctly. Example:
pcolor(rand(20));
shading flat
print('-depsc','figure.eps')
NOTE: You might see the appearance of thin, faint white lines along the anti-diagonals of each little square (depends on the OS & viewer). These are the edges of the graphics primitives that are used to render the image. However, this is not a flaw in MATLAB's export, but rather a fault in rendering in your EPS/PDF viewer. For e.g., with the default settings in Preview on my mac, these lines show up, whereas with the default in Adobe Reader 9.4, they don't appear.
If anyone is still interested in a workaround: Open the .eps-file with text editor and search for "interpolate". You'll probably find "/Interpolate true def" two or three times. Replace "true" with "false" and be happy :)
A note regarding Yoda's answer: in Preview in Mac OS X, you can make the thin white diagonal lines across each of the squares disappear by unchecking "Anti-alias text and screen art". Of course, the downside is that then any text (e.g. figure axes, etc) is not anti-aliased. Unfortunately, unchecking that has no effect on blurriness if you're using imagesc.
Another note is that if you use preview to make a pdf from your eps, the resulting pdf still displays correctly (non-blurry) when you open it in Acrobat.
I've been long struggling with this problem as well. So far, GSView is the only viewer I've found that displays the eps figures produced by Matlab (R2015b) correctly. eps2eps did not work for me (psutils 1.23).
The following eventually worked for me:
Export the figure to pdf, following the instructions here
pdf2ps file.pdf file.eps
I just wrote this simple drop-in replacement for imagesc. It doesn't support all but the most basic features, but I still hope it helps.
function h = imagesc4pdf(C)
[ny nx] = size(C);
px = bsxfun(#plus, [-0.5; 0.5; 0.5; -0.5], reshape(1:nx, [1 1 nx]));
py = bsxfun(#plus, [-0.5; -0.5; 0.5; 0.5], 1:ny);
n = numel(C);
px = reshape(repmat(px, [1 ny 1]), 4, n);
py = reshape(repmat(py, [1 1 nx]), 4, n);
h = patch(px, py, reshape(C,1,n), 'linestyle', 'none');
xlim([.5 nx+.5]);
ylim([.5 ny+.5]);
set(gca, 'ydir', 'reverse');
Apply opengl renderer to the figure
figure(gcf);
set(gcf,'renderer','opengl');
The blurring actually depends on the rendering software your viewer application or printer uses. To get good results all the time, make each pixel in your image an 8x8 block of pixels of the same color, i.e. resize the image like this:
im2 = imresize(im1, 8, 'nearest');
The blurring then only affects the pixels at the edge of each block. 8x8 blocks are best as they compress without nasty artifacts using DCT compression (sometimes used in eps files).
This page helped me a lot: http://tech.mof-mof.co.jp/blog/machine-learning-octave.html (written in Japanese, please use google translate for it)
And this is also helpful: Octave-Gnuplot-AquaTerm error: set terminal aqua enhanced title "Figure 1"...unknown terminal type"
I also answered at https://www.coursera.org/learn/machine-learning/discussions/weeks/2/threads/Dh-aRfqSEeaHSQ6l4xnh6g.
I reinstalled gnuplot like this:
$ brew cask install xquartz
$ brew cask install aquaterm
$ brew uninstall gnuplot
$ brew install gnuplot --with-aquaterm --with-x11 --with-qt # you can show other options by `$ brew options gnuplot`
You may edit ~/.octaverc like this:
setenv("GNUTERM", "qt")
and in octave window, after typing "system gnuplot", then
set pm3d interpolate 2, 2
After saving the file, open octave-cli.app, and type
imagesc(magic(3)), colorbar
I got this.