numpy 从2D点坐标列表生成图像的最快方法

gpnt7bae  于 2023-06-06  发布在  其他
关注(0)|答案(2)|浏览(150)

我有一个由其2D坐标(x,y)定义的点列表。

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(123)
x = 10*np.random.randn(2000)+32
y = 10*np.random.randn(2000)+32

我正在寻找以下代码的快速Python实现,它通过用这些点填充2D数组来形成图像:

im = np.zeros((64, 64))
dx = np.arange(64)
dy = np.arange(64)
for i in range(len(x)):
    xt, yt = x[i], y[i]
    ind_x = np.argmin((abs(dx-xt)))
    ind_y = np.argmin((abs(dy-yt)))
    im[ind_x, ind_y] += 1
    
plt.imshow(im)

我正在寻找最快的实现:

  • 案例1)大量积分
  • 情况2)图像中的大量像素

谢谢!

pbpqsu0x

pbpqsu0x1#

基本上,您正在尝试创建x和y的2D直方图。

np.random.seed(123)
x = 10*np.random.randn(2000)+32
y = 10*np.random.randn(2000)+32

# Create a 2D histogram of the x and y values
hist, xedges, yedges = np.histogram2d(x, y, bins=64, range=[[0, 64], [0, 64]])
plt.imshow(hist)

5vf7fwbs

5vf7fwbs2#

你可以试试这个:

import numpy as np
import matplotlib.pyplot as plt

N = 2000
M = 64

np.random.seed(123)
x = 10*np.random.randn(N)+32
y = 10*np.random.randn(N)+32

xint = np.clip(np.rint(x), 0, M - 1).astype(int)
yint = np.clip(np.rint(y), 0, M - 1).astype(int)
im4 = np.zeros((M, M))
np.add.at(im4, (xint, yint), 1)

plt.imshow(im4)

它给出:

相关问题