python背景图颜色_python – 使图形透明与彩色背景

编辑3:

已经澄清,基本问题是:

如何把’黑&在imshow制作的matplotlib图像前面的透明’面具?

掩模应由先前绘制的黑色和暗色的matplotlib产生.白色的身影.

以下代码通过访问和混合图形rgba位图来演示此功能:

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.cm as cm

import matplotlib.mlab as mlab

def get_rgba_bitmap(fig):

fig.canvas.draw()

tab = fig.canvas.copy_from_bbox(fig.bbox).to_string_argb()

ncols, nrows = fig.canvas.get_width_height()

return np.fromstring(tab, dtype=np.uint8).reshape(nrows, ncols, 4)

def black_white_to_black_transpa(rgba):

rgba[:, :, 3] = 255 - rgba[:, :, 0]

rgba[:, :, 0:3] = 0

def over(rgba1, rgba2):

if rgba1.shape != rgba2.shape:

raise ValueError("rgba1 and rgba2 shall have same size")

alpha = np.expand_dims(rgba1[:, :, 3] / 255., 3)

rgba = np.array(rgba1 * alpha + rgba2 * (1.-alpha), dtype = np.uint8)

return rgba[:, :, 0:3]

# fig 1)

fig1 = plt.figure(facecolor = "white")

fig1.set_dpi(300)

ax1 = fig1.add_subplot(1, 1, 1, aspect = "equal", axisbg = "black")

ax1.add_artist(plt.Circle((0., 0., .5), color = "white"))

ax1.set_xlim(-5, 5)

ax1.set_ylim(-5, 5)

bitmap_rgba1 = get_rgba_bitmap(fig1)

black_white_to_black_transpa(bitmap_rgba1)

# fig 2

fig2 = plt.figure(facecolor = "white")

fig2.set_dpi(300)

delta = 0.025

ax2 = fig2.add_subplot(1, 1, 1, aspect = "equal", axisbg = "black")

ax2.set_xlim(-5, 5)

ax2.set_ylim(-5, 5)

x = y = np.arange(-3.0, 3.0, delta)

X, Y = np.meshgrid(x, y)

Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)

Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)

Z = Z2-Z1 # difference of Gaussians

im = ax2.imshow(Z, interpolation='bilinear', cmap=cm.jet,

origin='lower', extent=[-5, 5, -5, 5],

vmax=abs(Z).max(), vmin=-abs(Z).max())

bitmap_rgba2 = get_rgba_bitmap(fig2)

# now saving the composed figure

fig = plt.figure()

fig.patch.set_alpha(0.0)

ax = fig.add_axes([0., 0., 1., 1.])

ax.patch.set_alpha(0.0)

ax.imshow(over(bitmap_rgba1, bitmap_rgba2))

plt.axis('off')

fig.savefig("test_transpa.png", dpi=300)

plt.show()

赠送:

我测试了你的初始光子测试案例,图片质量似乎没问题

现在,如果你想让图形背景透明:

>将fig1背景设置为’white’,即fig1 = plt.figure(facecolor =’white’),白色将传递给black_white_to_black_transpa时变为透明

>将fig2背景设置为透明fig2.patch.set_alpha(0.0),因为它将被存储而不会修改为bitmap_rgba2

>最后,在函数内部混合bitmap_rgba1和bitmap_rgba2时,请注意alpha通道(参见下面的可能修改)

06001

最后(?)编辑:

似乎在to_string_argb返回的数组与imshow预期的数组(rgb通道的顺序)之间存在不一致.一种可能的解决方案是将ax.imshow(over(bitmap_rgba1,bitmap_rgba2))更改为:

over_tab = over(bitmap_rgba1, bitmap_rgba2)

over_tab[:, :, 0:3] = over_tab[:, :, ::-1][:, :, 1:4]

ax.imshow(over_tab)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值