我已经使用 matplotlib 绘制了一些数据,并想从中心按圆裁剪它。
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(100)
Z = np.random.rand(10, 10)
fig, ax = plt.subplots()
ax.imshow(Z)
我尝试过屏蔽图像的想法:
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageDraw
np.random.seed(100)
Z = np.random.rand(10, 10)
fig, ax = plt.subplots()
ax.imshow(Z)
# Create same size alpha layer with circle
h, w = Z.shape
alpha = Image.new('L', Z.shape, 0)
draw = ImageDraw.Draw(alpha)
draw.pieslice([0,0,h,w],0,360,fill=255)
# Convert alpha Image to numpy array
npAlpha=np.array(alpha)
# Add alpha layer to RGB
Z = np.dstack((Z, npAlpha))
Image.fromarray(Z)
但是,我收到了这个错误:
TypeError: Cannot handle this data type: (1, 1, 2), <f8
是否可以仅使用 matplotlib 来完成?
您无法将 Alpha 通道添加到数值数组中。 Alpha 通道是图像的东西。对于 RGBA 图像。
因此,您首先需要将数组转换为 RGBA 图像(您已经在这样做,但只是隐式地执行:这就是当您使用 2d 数组调用
imshow
时在幕后发生的情况。所以唯一的变化是我们将自己做)。
当您打电话时,幕后会发生什么
plt.imshow(Z)
是
plt.imshow(plt.cm.viridis(Z))
所以分两步
rgba = plt.cm.viridis(Z)
plt.imshow(rgba)
在那里,您可以根据需要更改
rgba
部分
rgba = plt.cm.viridis(Z)
rgba[...,3] = npAlpha/255.0 # Because when type of image components is float, range is 0...1. And when uint8, 0...255. Yours is float
plt.imshow(rgba)