Have a transparent background in a plot exported from Octave

心不动则不痛 提交于 2021-02-05 12:21:02

问题


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:

  1. 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.

  2. 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.

  3. Option svgconvert is the only official documentation I found. But it would not apply to a png, e.g.

  4. 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:

  1. Saving a plot in Octave with transparent background

  2. Printing / saving a plot as a png file with an alpha channel issue in Octave

  3. 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:

  1. 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.

  2. The multiplication of im and tcolor 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!