可视化给定 numpy 数组的值分布

visualize the value distribution for a given numpy array

我有一个矩阵,例如生成如下

x = np.random.randint(10,size=(20,20))

如何根据给定值的分布可视化矩阵,即 6 换句话说,如何将矩阵显示为图像,其中对应矩阵条目等于6的像素将显示为白色,而其他像素将显示为黑色。

我想你想要这个:

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)