How can I print / save a plot as a png file with an alpha channel?
I tried Saving a plot in Octave with transparent background
I\'m using Octave 4.2.2, Ubu
(update: also see Sancho's nice answer here: Have a transparent background in a plot exported from Octave )
In general, adding transparency in octave is still not fully supported. My advice would be to produce your images as normal, and use an external tool to add transparency (which you could call from within octave via the system
function, if you'd like it to be part of a script).
The imagemagick suite can do what you want via the convert command, e.g.
convert myplot.png -fuzz 50% -transparent white myplot_transparent.png
(taken from here)
If you'd like to produce many 'layers', some of which have transparency, and then overlay them (which presumably is what you want the transparency for in the first place), you can also do this via imagemagick via:
convert bottomlayer.png toplayer.png -compose over -composite out.png
So a complete example in octave might look something like this:
t = [0:0.01:2*pi];
% Create bottom layer (no transparency needed)
plot (t, sin(t), 'r', 'linewidth', 3);
set(gcf, 'Position', [10, 10, 500, 500]);
axis([-1, 7, -1, 1]);
set(gca, 'Position', [0.1, 0.1, 0.8, 0.8]);
saveas(gcf, 'bottom.png');
% Create top layer, and make transparent (via imagemagick)
plot (t, cos(t), 'g', 'linewidth', 3);
set(gcf, 'Position', [10, 10, 500, 500]);
axis([-1, 7, -1, 1]);
axis off;
set(gca, 'Position', [0.1, 0.1, 0.8, 0.8]);
saveas(gcf, 'top.png');
system('convert top.png -fuzz 10% -transparent white top.png');
% Combine layers
system('convert bottom.png top.png -compose over -composite result.png');
%Visualise result in octave
imshow result.png
Resulting image:
It is not clear if you want to simply generate a file with a transparent background, or you want to handle the more general case of an arbitrary alpha channel for your image file.
Fortunately, it seems Octave can handle the second case as well. As pointed out here, transparency is not implemented for image or axes objects, but writing images to file with an alpha channel seems to work fine, at least in version 5.1.0.
So this would produce a transparent alpha channel for white (tcolor = [255 255 255]
)
im = print(gcf, '-RGBImage');
tcolor = [255 255 255];
alpha(:,:) = 255 * ( 1 - (im(:,:,1) == tcolor(1)) .* (im(:,:,2) == tcolor(2)) .* (im(:,:,3) == tcolor(3)) );
imwrite(im, 'myplot.png', 'Alpha', alpha);