首页 > 解决方案 > 如何在 numpy ndArray 中插入值?

问题描述

我有两个 ndArray。

ex: 
x = np.array([110,200, 500,100])
y = np.array([50,150,30,70])

现在基于它们的价值,我创建了一个图像。

x_shape = np.max(x)   #x_shape=500
y_shape = np.max(y)   #y-shape=150
image = np.zeros((x_shape+1, y_shape+1))

根据我现在的数据,我的图像大小是 (501,151)

现在,如何将 (x, y) 中的数据作为 x,y 对插入?我的意思是像素值:(110,50), (200,150), (500,30), (100,70) 我希望图像是白色的,其余的像素是暗的。我怎样才能做到这一点?

标签: pythonnumpynumpy-ndarray

解决方案


根据OP's own answer,可以通过使用矢量化方法对其进行改进:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([110,200, 500,100])
y = np.array([50,150,30,70])
x = np.floor(x / 10).astype(int)
y = np.floor(y / 10).astype(int)
x_shape = np.max(x)   # x_shape = 500
y_shape = np.max(y)   # y_shape = 150
image = np.zeros((x_shape + 10, y_shape + 10))
image[x, y] = 10

plt.imshow(image)

(公平地说,我不明白这是 OP 所追求的)。


编辑

要在不调整评论大小的情况下解决“可视化问题”:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([110, 200, 500, 100])
y = np.array([50, 150, 30, 70])

x_shape = np.max(x)
y_shape = np.max(y)
image = np.zeros((x_shape + 1, y_shape + 1))
image[x, y] = 10

plt.figure(figsize=(20, 20))
plt.imshow(image.transpose(), interpolation='nearest', aspect='equal')

推荐阅读