Getting screen units matlab for saving to pdf - matlab

I would like to export this picture to pdf format:
P2_tilde =
0.1029 0.4118 0.0245 0.1814 0.2794
0.3925 0.0234 0.0280 0.4626 0.0935
0.0928 0.1237 0.2680 0.2990 0.2165
0.0699 0.2219 0.0182 0.5106 0.1793
0.2611 0.0887 0.0837 0.3251 0.2414
figure('color',[1,1,1])
hBar2=bar3(P2_tilde);
colormap('pink')
set(hBar2,{'CData'},C);
set(gca,'xticklabel',surfaces)
set(gca,'yticklabel',surfaces)
surfaces={'Equipment','Patient','Hygiene products','Near-bed','Far-bed'};
colorbar
zlabel('Probability');
colormap('pink')
colorbar('location','southOutside')
set(gca,'xticklabel',surfaces)
set(gca,'yticklabel',surfaces)
surfaces={'Equipment','Patient','Hygiene products','Near-bed','Far-bed'};
zlabel('Probability');
Want to export to PDF format:
currentScreenUnits=get(gcf,'Units') % Get current screen units
currentPaperUnits=get(gcf,'PaperUnits') % Get current paper units
set(gcf,'Units',currentPaperUnits) % Set screen units to paper units
plotPosition=get(gcf,'Position') % Get the figure position and size
set(gcf,'PaperSize',plotPosition(3:4)) % Set the paper size to the figure size
set(gcf,'Units',currentScreenUnits) % Restore the screen units
print -dpdf ptilde % PDF called "ptilde.pdf"
Gives something completely off the page. Any thoughts how to center the figure on the canvas and make it only the size of the figure? Otherwise how can I trim it?

The PaperSizer parameter needs to be the actual size of the paper it will be printed on (the pdf file that will be displayed) not the size that the Matlab figure appears on the screen. For example, if you change it to this:
set(gcf,'PaperSize',[9,11])
you'll get something that looks reasonable.

I couldn't quite replicate your figure (errors in your code: need a definition for C) but use
f=figure('color',[1,1,1]);
%rest of figure code....
set(f,'PaperPositionMode','auto')
print -dpdf ptilde
Also, I'm not sure how to crop the pdf from within MATLAB, but if you want a cropped vector graphic use -depsc or -depsc2 as the print flag. see MATLAB help on print.

Related

Write Large Image as PDF in MATLAB

I am trying to write a large image to PDF (141"x24" at 300 DPI, so 42300 pixels x 7200 pixels). I can write the image as a png without a problem using imwrite(). However, imwrite() does not provide PDF as an output option. So, the alternatives I have seen online all do something like this:
pdffig = figure;
set(pdffig,'Units','Inches','Position',[0 0 141 24],'PaperSize',[141 24]);
pdfaxs = axes;
imshow(Im,'Parent',pdfaxs);
print(pdffig,'largeimage.pdf','-dpdf');
This code is creating a figure, setting some properties to make the figure 141x24 inches in size, showing the image on the figure axis, and then printing the figure contents to pdf.
Unfortunately, what happens is that the figure is resized to fit my screen when imshow() is called and then the printed pdf will have a small version of the image in the center of a large white pdf. What I actually want is for the image to take up the entire 141"x24" pdf. I have tried rearranging when the window size is set and when imshow() is called, but that doesn't help. Note that this works if the desired PDF size fits on my screen (e.g. if I was printing a 12"x12" PDF).
Any suggestions are appreciated!

How to open a txt file of IR temperatures as an image in matlab or other analysis software

I am using a therm-app camera to take infra-red photos of bats. I would like to draw around parts of the bat and find the hottest, coldest and average temperature and do further analysis.
The software that comes with the camera doesn't let me draw polygons so I would like to load the image in another program such as MATLAB or maybe imageJ (also happy to use Python or other if that would work).
The camera creates 4 files total:
I have a .jpg file, however when I open this in MATLAB it just appears as an image and I think it is just opening as a normal image, not sure how to accurately get the temperatures from this. I used the following to open it:
im=imread('C:\18. Bats\20190321_064039.jpg');
imshow(im);
I also have three other files, two are metadata (e.g. show date-time emissivity settings etc.) and one is a text file.
The text file appears to show the temperature of every pixel in the image.
e.g. (for a photo that had a minimum temperature of 15deg and max of 20deg it would be a text file with a minimum value of 1500 and maximum value of 2000)
1516 1530 1530 1540 1600 1600 1600 1600 1536 1536 ........
This file looks very useful, just wondering if there is some way I can open this as an image, probably in a program like MATLAB, which I think has image analysis so that I could draw around certain parts of the image (e.g. the wing of the bat) and find the average, max, min etc.
Has anyone had experience with this type of thing, can I just assign colours to numbers somehow? Or maybe other people have done it already and there is a much easier way. I will keep searching on the internet also and try to find out.
Alternatively maybe I need to open the .jpg image, draw around different parts, write a program to find out which pixels I drew around, find these in the txt file and then do averaging etc? Or somehow link the values in the text file to the .jpg file.
Sorry if this is the wrong place to ask, I can't find an image processing site on stack exchange.
All help is really appreciated, I will continue searching on the internet in the meantime.
the following worked in the end, it was much much easier than I thought it would be. Now a big fan of MATLAB, I thought it could take days to do this.
Just pasting here in case it is useful to someone else. I'm sure there is a more elegant way to write the code, however this is the first time I've used MATLAB in 20 years :p Use at your own risk, I haven't double checked I'm getting the correct results yet (though will do before I use it for anything important).
edit, since writing this I've found that the output .txt file of temperatures is actually sensor temperatures which need to be corrected for emissivity and background temperature to obtain the target temperatures. (One way to do this is to use the software which comes free with the camera to create new output .csv files of temperatures and use those instead).
Thanks to bla who put me on the right track with dlmread.
M=dlmread('C:\18. Bats\20190321_064039\20190321_064039_temps.txt') % read in the text file as a matrix (call it M)
% note that file seems to be a list of temperature values for each pixel
% e.g. 1934 1935 1935 1960 2000 2199...
M = rot90( M , 1 ) % rotate M anti-clockwise by 1*90 (All the pictures were saved sideways for some reason so rotate for easier viewing)
a = min(M(:)); % find the minimum temperature in the image
b = max(M(:)); % find the maximum temperature in the image
imresize(M,1.64); % resize the image to fit the computer screen prior to showing it on the screen
imshow(M,[a b]); % show image on the screen and fit the colours so that white is the value with the highest temperature in the image (b) and black is the lowest (a).
h = drawpolygon('FaceAlpha',0); % Let the user draw a polygon around the region of interest (ROI)
%(this stops code until polygon is drawn)
maskOfROI = h.createMask(); % For each pixel in the image assign a binary number, pixels inside the polygon (ROI) area are given 1 outside are 0
selectedValues = M(maskOfROI); % Now get the image values for all pixels where the mask value is '1' (i.e. all pixels within the polygon) and call this selectedValues.
averageTemperature = mean(selectedValues); % Get the mean of selectedValues (i.e. mean of the temperatures inside the polygon area)
maxTemperature = max(selectedValues); % Get the max of selectedValues
minTemperature = min(selectedValues); % Get the min of selectedValues

Save Matlab Simulink Model as PDF with tight bounding box

Given a Simulink block diagram (model), I would like to produce a 'Screenshot' to be used later in a LaTeX document. I want this screenshot to be PDF (vector graphic, -> pdflatex) with a tight bounding box, by that I mean no unneccessary white space around the diagram.
I have searched the net, searched stackexchange, searched the matlab doc. But no success so far. Some notes:
For figures, there are solutions to this question. I have a Simulink block diagram, it's different (see below).
I am aware of solutions using additional software like pdfcrop.
PDF seems to be the only driver that really produces vector graphics (R2013b on Win7 here). The EPS and PS output seems to have bitmaps inside. You zoom, you see it.
What I have tried:
1.
The default behaviour of print
modelName = 'vdp'; % example system
load_system(modelName); % load in background
% print to file as pdf and as jpeg
print(['-s',modelName],'-dpdf','pdfOutput1')
print(['-s',modelName],'-djpeg','jpegOutput1')
The JPEG looks good, tight bounding box. The PDF is centered on a page that looks like A4 or usletter. Not what I want.
2.
There are several parameters for printing block diagrams. See the Simulink reference page http://www.mathworks.com/help/simulink/slref/model-parameters.html. Let's extract some:
modelName = 'vdp'; % example system
load_system(modelName); % load in background
PaperPositionMode = get_param(modelName,'PaperPositionMode');
PaperUnits = get_param(modelName,'PaperUnits');
PaperPosition = get_param(modelName,'PaperPosition');
PaperSize = get_param(modelName,'PaperSize');
According to the documentation, PaperPosition contains a four element vector [left, bottom, width, height]. The last two elements specify the bounding box, the first two specify the distance of the lower left corner of the bounding box from the lower left corner of the paper.
Now when I print the PDF output and measure using a ruler, I find the values of both the bounding box and the position of its lower left corner are totally wrong (Yes, I have measured in PaperUnits). That's a real bummer. I could have calculated the margins to trim off the paper to be used later in \includegraphics[clip=true,trim=...]{pdfpage}.
3.
Of course what I initially wanted is a PDF that is already cropped. There is a solution for figures, it goes like this: You move the bounding box to the lower left corner of the paper and than change the paper size to the size of the bounding box.
oldPaperPosition = get_param(modelName,'PaperPosition');
set_param(modelName,'PaperPositionMode','manual');
set_param(modelName,'PaperPosition',[0 0 oldPaperPosition(3:4)]);
set_param(modelName,'PaperSize',oldPaperPosition(3:4));
For simulink models, there are two problems with this. PaperSize is a read-only parameter for models. And changing the PaperPosition has no effect at all on the output.
I'm running out of ideas, really.
EDIT ----------------------------------
Allright, to keep you updated: I talked to the Matlab support about this.
In R2013b, there are bugs causing wrong behaviour of PaperPositionMode and the bounding box from PaperPostion to be wrong.
There is no known way to extract the scale factor from print.
They suggested to go this way: Simulink --(print)--> SVG --(Inkscape)--> PDF. It works really good this way. The (correct) bounding box is an attribute of the svg node and the scale factor when exporting to SVG is always the same. Furthermore, Inkscape produces an already cropped PDF. So this approach solves all my problems, just you need Inkscape.
You can try export_fig to export your figures. WYSIWYG! This function is especially suited to exporting figures for use in publications and presentations, because of the high quality and portability of media produced.
Why you don't like to use pdfcrop?
My code works perfectly, and everything is inside Matlab:
function prints(name)
%%Prints Print current simulink model screen and save as eps and pdf
print('-s', '-depsc','-tiff', name)
print('-s', '-dpdf','-tiff', name)
dos(['pdfcrop ' name '.pdf ' name '.pdf &']);
end
You just have to invoke pdfcrop using "dos" command, and it's works fine!
on 2021a you have exportgraphics.
beatiful pdf images.
figure(3);
plot(Time.Data,wSOHO_KpKi.Data,'-',Time.Data,Demanded_Speed.Data,'--');
grid;
xlh = xlabel('$\mathrm{t\left [ s \right ]}$','interpreter','latex',"FontSize",15);
ylh = ylabel('$\mathrm{\omega _{m}\left [ rads/s \right ]}$','interpreter','latex',"FontSize",15);
xlh.Position(2) = xlh.Position(2) - abs(xlh.Position(2) * 0.05);
ylh.Position(1) = ylh.Position(1) - abs(ylh.Position(1) * 0.01);
exportgraphics(figure(3),'Grafico de Escalon Inicial velocidad estimada por algoritmo SOHO-KpKi.pdf');

How to save custom-sized figures [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Printing a MATLAB plot in exact dimensions on paper
How do I save a plotted image and maintain the original image size in MATLAB?
I have recently been trying to create a custom-sized graph in MATLAB and save it automatically using the saveas function. In particular, I am having issues saving the files in the size that I create them. Roughly speaking, my code is as follows:
mygraph = figure('Position',[1,20,1280,1024]);
% creates a figure positioned 1 px from the left of the screen
% 20 px from the bottom of the screen
% that is 1280 px in length and 1024 px in height
% some code to create graph
saveas(mygraph,'mygraphfilename','emf')
% saves figure as mygraphfilename.emf.
So far, my code works fine in that it can create a custom sized graph on my screen, but it seems to save the pictures themselves in a default size. The weird thing is that if I do not use the saveas function and save the figure manually, then the image retains its size.
For clarification purposes, I'm currently saving the graphs as emf, though I'm also open to using jpg/png/bmp if works fine too.
Try setting the following:
set(mygraph, 'PaperPositionMode','auto') %# WYSIWYG
print -dmeta -r0 file.emf

MATLAB: print a figure to pdf as the figure shown in the MATLAB

I am trying to export (save as, print) a figure into .pdf format. However, no matter how I configure the setting, there are large margins around the figure.
When I export the figure into .eps format, there is no such problem --- i.e. the figure just looks like it is displayed in the MATLAB.
How could I export the figure into .pdf format, which looks the same as it is shown in the MATLAB?
You can automate the process above by adding the following lines of code immediately after the plot command.
set(gcf,'Units','inches');
screenposition = get(gcf,'Position');
set(gcf,...
'PaperPosition',[0 0 screenposition(3:4)],...
'PaperSize',[screenposition(3:4)]);
print -dpdf -painters epsFig
The first two lines measure the size of your figure (in inches). The next line configures the print paper size to fit the figure size. The last line uses the print command and exports a vector pdf document as the output.
You can try the following:
1) After you plot the figure in MATLAB, go to 'File->Export Setup', and input the size of the output you want. For example, Width: 6 inches, Height: 5 inches. Then click 'Apply to Figure' button.
2) Don't close the 'Export Setup' window. Go to 'File->Print Preview->Paper', input the same size in the Width and Height options.
3) Don't close the 'Print Preview' window. Go back to the 'Export Setup' window, and click 'Export', then select pdf format and save it.
4) Check the output PDF file, you'll see it is perfect.
I found the solution in blog post Export figure to PDF in MATLAB.
2-lines script, for exporting to PDF in landscape A4 (assuming your plot is the "current figure"):
%-------------------------------------------------------------------
% resize paper as a landscape-A4 and reposition figure accordingly
set( gcf,'PaperSize',[29.7 21.0], 'PaperPosition',[0 0 29.7 21.0])
% export to PDF file 'YourFileName.pdf'
print -dpdf 'YourFileName'
%-------------------------------------------------------------------
Any other tweak : check the Figure properties - simply "get( gcf )" on the command window