从2d numpy数组创建2d直方图

时间:2017-10-04 07:39:03

标签: python numpy matplotlib

我有一个像这样的numpy数组:

[[[0,0,0], [1,0,0], ..., [1919,0,0]],
[[0,1,0], [1,1,0], ..., [1919,1,0]],
...,
[[0,1019,0], [1,1019,0], ..., [1919,1019,0]]]

创建我使用的功能(感谢@Divakar和@unutbu帮助解决其他问题):

def indices_zero_grid(m,n):
     I,J = np.ogrid[:m,:n]
     out = np.zeros((m,n,3), dtype=int)
     out[...,0] = I
     out[...,1] = J
     return out

我可以通过命令访问此数组:

>>> out = indices_zero_grid(3,2)
>>> out
array([[[0, 0, 0],
        [0, 1, 0]],

       [[1, 0, 0],
        [1, 1, 0]],

       [[2, 0, 0],
        [2, 1, 0]]])
>>> out[1,1]
array([1, 1,  0])

现在我想绘制2d直方图,其中(x,y)(out [(x,y))是坐标,第三个值是出现次数。我尝试使用普通的matplotlib图,但是我每个坐标都有这么多的值(我需要1920x1080),程序需要太多的内存。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要尺寸为1920x1080的图像,该图像根据(x, y)的值为坐标out[x, y]上的像素着色。

在这种情况下,您可以使用

import numpy as np
import matplotlib.pyplot as plt

def indices_zero_grid(m,n):
     I,J = np.ogrid[:m,:n]
     out = np.zeros((m,n,3), dtype=int)
     out[...,0] = I
     out[...,1] = J
     return out

h, w = 1920, 1080
out = indices_zero_grid(h, w)
out[..., 2] = np.random.randint(256, size=(h, w))
plt.imshow(out[..., 2])
plt.show()

产生

enter image description here

请注意,未使用其他两个"列",out[..., 0]out[..., 1]。这表明此处并不真正需要indices_zero_grid

plt.imshow可以接受一个形状数组(1920,1080)。此数组在数组中的每个位置都有一个标量值。数组的结构告诉imshow每个单元格的颜色。与散点图不同,您不需要自己生成坐标。

相关问题