【发布时间】:2020-03-29 18:46:57
【问题描述】:
我有一个矩阵,例如,生成如下
x = np.random.randint(10,size=(20,20))
如何根据给定值的分布可视化矩阵,即 6 换句话说,如何将矩阵显示为图像,其中对应矩阵条目等于6的像素将显示为白色,而其他像素将显示为黑色。
【问题讨论】:
标签: python-3.x numpy scipy scikit-image numpy-ndarray
我有一个矩阵,例如,生成如下
x = np.random.randint(10,size=(20,20))
如何根据给定值的分布可视化矩阵,即 6 换句话说,如何将矩阵显示为图像,其中对应矩阵条目等于6的像素将显示为白色,而其他像素将显示为黑色。
【问题讨论】:
标签: python-3.x numpy scipy scikit-image numpy-ndarray
我想你想要这个:
from PIL import Image
import numpy as np
# Initialise data
x = np.random.randint(10,size=(20,20),dtype=np.uint8)
# Make all pixels with value 6 into white and all else black
x[x==6] = 255
x[x!=255] = 0
# Make PIL Image from Numpy array
pi = Image.fromarray(x)
# Display image
pi.show()
# Save PIL Image
pi.save('result.png')
【讨论】:
通过黑白图像显示给定值的分布的最简单方法是使用布尔数组,如x == 6。如果您希望通过用自定义颜色替换黑白来提高可视化效果,NumPy 的where 将派上用场:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randint(10, size=(20, 20))
value = 6
foreground = [255, 0, 0] # red
background = [0, 0, 255] # blue
bw = x == value
rgb = np.where(bw[:, :, None], foreground, background)
fig, ax = plt.subplots(1, 2)
ax[0].imshow(bw, cmap='gray')
ax[0].set_title('Black & white')
ax[1].imshow(rgb)
ax[1].set_title('RGB')
plt.show(fig)
【讨论】: