Making the "Region of Interest" (ROI) transparent in MATLAB - matlab

I've already made a function to cut out the image, and the part I cut out has a black background. I'm trying to make the black part transparent, then I can generate an image sequence that I can create a video with. I've tried converting the image to a double and then replacing the 0 values with NaN:
J = imread('imgExample.jpg');
J2 = im2double(J);
J2(J2 == 0) = NaN;
imwrite(J2, 'newImg.jpg');
but when I convert it into a video, it doesn't seem to stay. Is there any way to get the black part of the image to be transparent?

From clarifications in comments, you are trying to create a video format that supports alpha transparency using matlab.
In general this seems impossible using matlab alone (at least in matlab 2013 which is the version I use). If you'd like to check if the newest matlab supports videos with alpha transparency, type doc videowriter and have a look at the available formats. If you see anything with transparency options there, take it from there. But the most I see on mine is 24bit RGB videos (i.e. three channels, no transparency).
So matlab does not have the ability to produce native .avi video with alpha transparency.
However, note that this is a very rare video format anyway, and even if you did manage to produce such a video, you would still have to find a suitable viewer which supports playing videos with transparency!
It's therefore important for you to tell us your particular use-case because it may be you're actually trying to do something much simpler (which may or may not be solvable via matlab) (i.e. a case of the XY Problem
E.g. you may be trying to create a video with transparency for the web instead, like here https://developers.google.com/web/updates/2013/07/Alpha-transparency-in-Chrome-video
If this is the case, then I would recommend you attempting the method outlined there; you can create individual .png "frames" with transparency in matlab using the imwrite function. have a look at its documentation, particularly the section about png images and the 'Alpha' property. But beyond that, you'd need an external tool to combine them into a .webm file, since matlab doesn't seem to have a tool like that (at least none that I can see at a glance; there might be a 3rd-party toolkit if you look on the web).
Hope this helps.

Related

Convert SVG to PDF using Python, rsvg & Cairo

I have managed to read SVG using rsvg and output it to PNG via Cairo, in Python.
Despite there being MANY similar questions, I've not seen any documentation on how to convert SVG into PDF through rsvg & cairo. I am aware of the command-line 'rsvg'/'rsvp-convert' tools, but want to incorporate the functionality into my Python code instead. No launching subprocess either.
For the sake of example, here's basically what I currently use to render PNG:
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
ctx = cairo.Context(img)
handler= rsvg.Handle(None, svgstr)
handler.render_cairo(ctx)
img.write_to_png(pngfilepath)
The question is: how would the code be changed to output PDF instead, so that vector format is kept; rasterization must not happen.
Replace your call to cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) with cairo.PDFSurface(filename, width_in_points, height_in_points). I don't know what the default scaling of the PDF surface is, but hopefully you can continue to use the same width and height values as before.
Since you explicitely mention that rasterization must now happen: Cairo "does its best" not to raster things, but there are combinations where cairo has to fall back to rasterized images. You can control the resolution of this images via the set_fallback_resolution method.
Reasons for rasterization include combinations of operations that cannot be expressed in PDF (sorry, I don't know details) and if some rasterized image is drawn to the PDF surface.

visualising l*a*b space values in matlab or any software

I have table of l,a,b values and want to visualise these colors in matlab (or any other suitable software). Is there any quick way like series of rectangles filled with color values from the table?
There are several versions of the Lab color space, but presumably you're referring to most common, CIELAB. You can use imwrite in Matlab to create a TIFF image with 'cielab' specified for the 'Colorspace' option. I wouldn't trust Matlab as a viewer for the resultant images though. Photoshop in lab mode (from the menu bar: Image > Mode > Lab Color) would be a good choice if you want work with and see the closest thing to the actual CIELAB space. Other viewers/editors may convert to RGB or CMYK before rendering to the screen (likely without warning you), but maybe you don't mind. If you just want to convert from CIELAB to RGB, you might find these functions useful.
After lots of research, I found out there is a plugin called 'color inspector' that can be used along with ImageJ (all opensource tools). Have excellent capacity to view and analyse different color space. Even it has some color tools that matlab yet to have. here is imageJ: http://rsbweb.nih.gov/ij/download.html
and the plugin
http://rsb.info.nih.gov/ij/plugins/color-inspector.html
Hope this is useful to someone

Matlab imwrite() quality

I'm very new to Matlab, though I know a few other programming languages, so please forgive me if this is something simple. I have not been able to find any answers to this, either on StackOverflow or elsewhere.
I produce a figure using the following code:
figure(6),imageplot(P); drawnow;
Which looks like this:
I then save this image to my computer using the following commands:
imwrite(P, 'images/plot.png');
And the resulting image is tiny, and missing some of the color information:
If, however, I utilize the save function in the open figure (image #1) and save it manually, I get exactly what I want, which is that exact image stored on my computer.
How would I program that? I assumed that imwrite() would just write the image directly, but apparently I'm doing something wrong. Any advice? Perhaps it has something to do with the imageplot command? I cannot seem to get that to work in imwrite.
Update: Based on the comments below, I have begun using "imresize" with the "nearest" option. This scales the image properly, but the resulting image is still curiously darker (and therefore has less information) than if I hit the "save" button in the figure.
Image saved from figure:
Image using "imresize" with "nearest" option:
The MATLAB imwrite command saves exactly the number of pixels as specified in your image matrix. This is the actual result of your computation; the reason the output is "tiny" is because it is supposed to be. To make it larger, would be to simply scale/zoom it as required.
The save figure option however does something quite different: it rasterizes the the output you obtain in the figure window and gives you the option for saving it as an image. This is evident in the fact that when you do so, you obtain a white background in addition to your result which is really just the grey background you see before you save it; this can be adjusted by resizing the figure window before utilizing the save option.
If you're looking to simply make the output figure larger, I would recommend using something along the lines of the imresize command.
Say, if you want the default size to be twice the size of the real result, simply use:
imresize(P, 2.0);
For more options, try help imresize.
The command you need for the "Save As..." functionality of figures is called "print". I often use
print(gcf, '-dpng', 'some_filename.png')
or
print(gcf, '-depsc', 'some_filename.eps','-r0')
to save a figure as it is shown on screen. The format png offers a small filesize and excellent quality, and it is understood by most image viewers and browsers. The eps format is a vector format, which I use for printig. The '-r0' option specifies "use the same size as given by the screen resolution" for the vector format properties.

How to visualize correlation matrix as a schemaball in Matlab

I have 42 variables and I have calculated the correlation matrix for them in Matlab. Now I would like to visualize it with a schemaball. Does anyone have any suggestions / experiences how this could be done in Matlab? The following pictures will explain my point better:
In the pictures each parabola between variables would mean the strength of correlation between them. The thicker the line is, the more correlation. I prefer the style of picture 1 more than the style in picture 2 where I have used different colors to highlight the strength of correlation.
Kinda finished I guess.. code can be found here at github.
Documentation is included in the file.
The yellow/magenta color (for positive/negative correlation) is configurable, as well as the fontsize of the labels and the angles at which the labels are plotted, so you can get fancy if you want and not distribute them evenly along the perimeter/group some/...
If you want to actually print these graphs or use them outside matlab, I suggest using vector formats (eg eps). It's also annoying that the text resizes when you zoom in/out, but I don't know of any way to fix that without hacking the zoom function :/
schemaball % demo
schemaball(arrayfun(#num2str,1:10,'uni',false), rand(10).^8,11,[0.1587 0.8750],[0.8333 1],2*pi*sin(linspace(0,pi/2-pi/20,10)))
schemaball(arrayfun(#num2str,1:50,'uni',false), rand(50).^50,9)
I finished and submitted my version to the FEX: schemaball and will update the link asap.
There are a some differences with Gunther Struyf's contribution:
You can return the handles to the graphic object for full manual customization
Labels are oriented to allow maximum left-to-rigth readability
The figure stretches to fit labels in, leaving the axes unchanged
Syntax requires only correlations matrix (but allows optional inputs)
Optimized for performance.
Follow examples of demo, custom labels and creative customization.
Note: the first figure was exported with saveas(), all others with export_fig.
schemaball
x = rand(10).^3;
x(:,3) = 1.3*mean(x,2);
schemaball(x, {'Hi','how','is','your','day?', 'Do','you','like','schemaballs?','NO!!'})
h = schemaball;
set(h.l(~isnan(h.l)), 'LineWidth',1.2)
set(h.s, 'MarkerEdgeColor','red','LineWidth',2,'SizeData',100)
set(h.t, 'EdgeColor','white','LineWidth',1)
The default colormap:
To improve on screen rendering you can launch MATLAB with the experimental -hgVersion 2 switch which produces anti/aliased graphics by default now (source: HG2 update | Undocumented Matlab). However, if you try to save the figure, the file will have the usual old anti-aliased rendering, so here's a printscreen image of Gunther's schemaball:
Important update:
You can do this in Matlab now with the FileExchange submission:
http://www.mathworks.com/matlabcentral/fileexchange/48576-circulargraph
There is an exmample by Matlab in here:
http://uk.mathworks.com/examples/matlab/3859-circular-graph-examples
Which gives this kind of beautiful plots:
Coincidentally, Cleve Moler (MathWorks Chief Mathematician) showed an example of just this sort of plot on his most recent blog post (not nearly as beautiful as the ones in your example, and the connecting lines are straight rather than parabolic, but it looks functional). Unfortunately he didn't include the code directly, but if you leave him a comment on the post he's usually very willing to share things.
What might be even nicer for you is that he also applies (and this time includes) code to permute the rows/columns of the array in order to maximize the spatial proximity of highly connected nodes, rather than randomly ordering them around the circumference. You end up with a 'crescent'-shaped envelope of connecting lines, with the thick bit of the crescent representing the most highly connected nodes.
Unfortunately however, I suspect that if you need to enhance his code to get the very narrow, high-resolution lines in your example plots, then MATLAB's currently non-anti-aliased graphics aren't quite up to it yet.
I've recently been experimenting with MATLAB data and the D3 visualization library for similar graphs - there are several related types of circular visualizations you may be interested in and many of them are interactive. Another helpful, well-baked, and freely available option is Circos which is probably responsible for most of the prettier versions of these graphs you've seen in popular press.

MATLAB and high quality EPS figures

I am looking to export my MATLAB plot as a high quality figure. Specifically, I would like to save it as a vector based file format such as EPS or SVG.
I have tried print and saveas commands:
saveas(h,'myFileName','epsc2');
print('-r150','-depsc2', 'myFilename');
On all occasions this produces poor quality parts of the graph, although the axis-labels are indeed vector. Why does MatLab do some horrible rendering before putting it into an EPS?
Example of poor quality plot here:
http://users.ox.ac.uk/~pemb2372/myFileName.eps
Edit:
It is also worth noting that if you use a Mac viewing an EPS file from Matlab, 'Preview' app may render inner graph content rasterized and poor quality, while leaving the axis and labels vectorized and high quality. This is very misleading but when you open said EPS file in, for example, Inkscape, the quality is actually vector and quite high.
Edit 2:
My university hosting account has expired, so you can no longer view the figure. Suffice it to say that it showed a poor quality raster-style plot within high quality beautiful axis lines, ticks and labels.
I thought I would share the issue I had, and how I overcame it...
I was getting terrible results because I had the wrong renderer set to default. In my startup.m, I had the zbuffer renderer enabled. This is an example eps output.
I made that eps output with: print(gcf,'-depsc2','filename.eps'). This eps is so OBVIOUSLY rasterised. It makes me angry at matlab. Then, I had a brainwave - perhaps my default renderer zbuffer is interfering with the image save process. So, adding the line:
set(gcf,'renderer','painters')
and running the print command as before, here is the output:
Note that I just took screenshots of the eps output files at 100%. And I can confirm the second image is actually vector. Here is a good question/explanation on choosing Renderers in MATLAB.
Matlab can export to pdf with better quality than EPS, but with its own caveats of setting decent margins and font sizes.
edit:
Examples are similar to the EPS case as explained in the help of e.g. print:
saveas(gcf,'filename.pdf')
or
print('-dpdf','filename.pdf')
You might also want to take a look at the PaperSize, PaperPosition and PaperUnits properties of your figure (by means of the set and get functions).
edit: Another option is to use one of the functions available on FileExchange such as the ones mentioned by #user664303 below. My personal favorite for use with LaTeX is matlab2tikz for which the latest version can be gotten from GitHub. Together with the external library of TikZ, I think this delivers some of the most nicest graphs around.
Probably it's also best to mention that I have been actively involved in the matlab2tikz project since 2012.
The export_fig function on the MATLAB file exchange is a reasonably reliable way of accurately exporting figures to eps and pdf (as well as bitmap formats) in MATLAB.
The plot2svg function, also from the file exchange, allows you to export in svg format. It provides some additional benefits, such as being able to export translucent patch objects in vector format.
A comparison of exporting methods is given in this blog post.
I always acquire the final plots (those which are supposed to be inserted into papers and publications) by matplotlib library of python.
You can bet on the amazing quality of the generated plots, both .pdf and .eps formats.