如何在python中创建透明波形

问题描述 投票:0回答:1

我不知道如何使图表透明。我有一个音频波形图,并用背景填充空间,我正在尝试,但背景仍然出现在图表上。

def generate_waveform_image(save_dir, audio_file, output_filename, color='white', alpha=0, figsize=(12, 2), dpi=75):
        fig, ax = plt.subplots(figsize=figsize, dpi=dpi, frameon=False)
        plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
        samples, sr = librosa.load(audio_file, sr=None, mono=True)
        times = np.arange(len(samples)) / sr
        ax.plot(times, samples, color=color, alpha=alpha, linewidth=0.1)
        ax.margins(0, 0)
        ax.axis('off')
        plt.savefig(os.path.join(save_dir, f'{output_filename}.png'), transparent=True, bbox_inches='tight',
                    pad_inches=0)

我尝试了所有方法,仍然是,背景填充了整个图像,但我需要它是这样的:

enter image description here

ax.fill_between(times, -1, 1, color='gray', alpha=1)
python matplotlib transparent
1个回答
1
投票

以下方法:

  • 可选择设置
    'agg'
    后端,因此屏幕上不会显示任何内容
  • 绘制波前,并将边距设置为零
  • 使图形的背景透明
  • 需要
  • fig.canvas.draw()
    来填充像素
  • 像素被复制到 numpy 数组
  • alpha 值反转(透明背景变为不透明,不透明曲线变为透明,曲线半透明边框的透明度反转
  • 所有像素都涂成黑色(同时保持新的透明度)
  • numpy 数组通过 PIL(Python 的标准图像库)保存到文件
import matplotlib; matplotlib.use('agg')

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

fig, ax = plt.subplots(figsize=(12, 2))

values = np.random.randn(5000) * np.random.randn(5000).cumsum()
ax.plot(values, color='black', lw=1)
ax.margins(x=0)  # no margins left and right
ax.axis('off')  # hide the axes
fig.patch.set_alpha(0)  # transparent
plt.subplots_adjust(bottom=0, left=0, top=1, right=1)  # remove padding around the main plot
fig.canvas.draw()  # "draw" is needed to fill in the pixels

buffer, (width, height) = fig.canvas.print_to_buffer()
data = np.array(np.frombuffer(buffer, np.uint8).reshape((height, width, 4)))

data[:, :, 3] = 255 - data[:, :, 3]  # invert the transparency of all pixels
data[:, :, :3] = 0  # make all pixels black while keeping the new transparency

img = Image.fromarray(data)
img.save("transparent_waveform.png")

这就是 Gimp 内部图像的样子:

© www.soinside.com 2019 - 2024. All rights reserved.