简体   繁体   English

Python numpy 数组 - 用坐标值快速填充

[英]Python numpy array - fill fast with values of coordinates

I have a huge number of points that represent centers of gravity of rectangles.我有大量代表矩形重心的点。 My task is to create a 3D numpy array of a shape (len(x_values) * len(y_values), 4, 2) that would contain [x,y] coordinates of all 4 tops of those rectangles.我的任务是创建一个形状为 (len(x_values) * len(y_values), 4, 2) 的 3D numpy 数组,其中包含这些矩形所有 4 个顶部的 [x,y] 坐标。

Example:例子:

  • center of gravity of the first rectangle is [4.0, 5.0]第一个矩形的重心是 [4.0, 5.0]
  • rectangle width (always a constant) = 2.0矩形宽度(始终为常数)= 2.0
  • rectangle height (always a constant) = 3.0矩形高度(始终为常数)= 3.0
  • the first set of points (tops of a rectangle) in the numpy array would be: numpy 数组中的第一组点(矩形的顶部)将是:
[[[3.  3.5]     # 4.0 - 2.0/2, 5.0 - 3.0/2 ... first top
  [3.  6.5]     # 4.0 - 2.0/2, 5.0 + 3.0/2 ... second top
  [5.  6.5]     # 4.0 + 2.0/2, 5.0 + 3.0/2 ... third top
  [5.  3.5]]    # 4.0 + 2.0/2, 5.0 - 3.0/2 ... fourth top
  
  ...           # other points
]  

I wrote this code:我写了这段代码:

import numpy as np
import random


# Just an example of points that represent centers of gravity of rectangles; 500 000 in total
x_values = [random.uniform(0, 10) for _ in range(1000)]
y_values = [random.uniform(0, 10) for _ in range(500)]

WIDTH = 2.0
HEIGHT = 3.0

my_points = np.zeros(shape=(len(x_values) * len(y_values), 4, 2), dtype=np.float64)

ii = 0
for y in y_values:
    for x in x_values:
        # [x, y] ... center of gravity of a rectangle
        my_points[ii][0][0] = x - WIDTH*0.5
        my_points[ii][0][1] = y - HEIGHT*0.5
        my_points[ii][1][0] = x - WIDTH*0.5
        my_points[ii][1][1] = y + HEIGHT*0.5
        my_points[ii][2][0] = x + WIDTH*0.5
        my_points[ii][2][1] = y + HEIGHT*0.5
        my_points[ii][3][0] = x + WIDTH*0.5
        my_points[ii][3][1] = y - HEIGHT*0.5
        ii += 1

However, this approach is really slow for huge number of points.但是,对于大量点,这种方法确实很慢。 Is there a better and faster way how to fill the array?有没有更好更快的方法来填充数组?

The speedup comes from vectorizing the assignment and eliminating the python loop.加速来自矢量化分配和消除 python 循环。

my_points = np.empty(shape=(len(x_values) * len(y_values), 4, 2), dtype=np.float64)

x = np.tile(x_values, len(y_values))
y = np.repeat(y_values, len(x_values))

my_points[:,1,0] = my_points[:,0,0] = x - WIDTH*0.5
my_points[:,3,1] = my_points[:,0,1] = y - HEIGHT*0.5
my_points[:,2,1] = my_points[:,1,1] = y + HEIGHT*0.5
my_points[:,3,0] = my_points[:,2,0] = x + WIDTH*0.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM