在 Octave 中打印/保存一个带有 alpha 通道问题的 png 文件

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

如何将绘图打印/保存为带有 alpha 通道的 png 文件?

我试过了 Saving a plot in Octave with transparent background

我正在使用 Octave 4.2.2、Ubuntu 18.04 64 位和 graphics_toolkit fltk

t = [0:0.01:2*pi]; x = sin (t);
plot (t, x);
set(gcf, 'Position',  [10, 10, 500, 500]);
print(gcf,'-dpngalpha', 'myplot.png');

I get an error error: print: unknown device pngalpha error: called from print_parse_opts at line 265 column 5 print at line 316 column 8

请注意:Octave 在 5.2 上,此问题在下面有解决方法...

(更新:另见 Sancho 的精彩回答:Have a transparent background in a plot exported from Octave


总的来说,仍然不完全支持在八度音程中添加透明度。我的建议是正常生成图像,并使用外部工具来增加透明度(如果您希望它成为脚本的一部分,您可以通过 system 函数从八度内调用)。

imagemagick 套件可以通过 convert 命令做你想做的事,例如

convert  myplot.png  -fuzz 50%  -transparent white  myplot_transparent.png

(取自here

如果你想制作很多'layers',其中一些是透明的,然后覆盖它们(这可能是你首先想要透明的原因),你也可以这样做通过 imagemagick 通过:

convert  bottomlayer.png  toplayer.png  -compose over  -composite out.png

所以八度音阶的完整示例可能如下所示:

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

结果图像:

不清楚您是想简单地生成一个具有透明背景的文件,还是想为您的图像文件处理更一般的任意 alpha 通道。

幸运的是,Octave 似乎也可以处理第二种情况。 正如所指出的 , image 或 axes 对象没有实现透明度,但使用 alpha 通道将图像写入文件似乎工作正常,至少在 5.1.0 版本中是这样。

所以这将为白色生成一个透明的 alpha 通道 (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);