问题
I am using portable Octave 5.1.0 under Win 10. I mean to write a plot to png with transparent background.
Disclaimer: This question is similar to the two linked below. I opted asking the present different question since I am adding further relevant information (by the same token, question #2 below was not a dupe of #1).
This is what I found:
print(gcf,'-dpngalpha', 'myplot.png');
, suggested in Saving a plot in Octave with transparent background, does not work for me. It is remarkable that I did not find documentation on this option.This answer has a couple of issues for me: 1) for some unknown reason
convert
does nothing. 2) The requirement of an external package makes it cumbersome. For instance, I cannot simply send my Octave code to someone else for him to use it.Option
svgconvert
is the only official documentation I found. But it would not apply to a png, e.g.imwrite seems to have the capability to write with transparency, but I couldn't find a way to transform a plot into and image suitable for
imwrite
. (See also Matlab documentation). Perhaps this is a possible route...
Is there any option available in Octave?
Related:
Saving a plot in Octave with transparent background
Printing / saving a plot as a png file with an alpha channel issue in Octave
http://mlab.no/blog/2014/06/image-transparency-overlay-with-gnu-octave-using-ycbcr/
回答1:
The imwrite
option seems to work. First create the image file img_fname
, then create an alpha layer for it.
It would be interesting to know if one could avoid the intermediate non-transparent file.
EDIT: I managed to create the image directly from my plot, instead of requiring the intermediate file.
x = -10:0.1:10;
plot (x, sin (x));
# Print figure directly to image instead of file
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, 'temp.png', 'Alpha', alpha);
Notes:
With a little simple algebra one could add transparency for any number of colors, and any opacity level for each color. Moreover, one could move this into a function.
The multiplication of
im
andtcolor
could be possibly vectorized as well.
Related:
https://www.mathworks.com/matlabcentral/answers/57664-how-to-add-alpha-channel-to-the-image-and-convert-that-image-into-png-format
来源:https://stackoverflow.com/questions/64460791/have-a-transparent-background-in-a-plot-exported-from-octave