【问题标题】:Calculate the area of a 2d closed polygon using numpy使用 numpy 计算二维封闭多边形的面积
【发布时间】:2021-05-29 20:14:03
【问题描述】:

我有一个 2d numpy 数组,我想评估以下等式。 是否有一种 numpy like(vectorized) 方式来实现此评估,而不仅仅是迭代值?

额外的问题,有没有办法(再次矢量化)将产品的每个结果保存在一个新的 1d numpy 数组中? 提前致谢

顺便说一句,公式是从这个网站找到的:https://www.seas.upenn.edu/~ese502/lab-content/extra_materials/Polygon%20Area%20and%20Centroid.pdf

【问题讨论】:

  • 请提供一些有代表性的数据和您相应的预期结果。至少对我来说,不清楚你是否有一个顶点坐标列表,或者一个 Numpy 顶点坐标数组,或者一个 Numpy 数组中的蒙面多边形区域。谢谢。
  • 喂?你放弃这个问题了吗?

标签: numpy array-broadcasting


【解决方案1】:

你可以使用numpy.roll如下:

import numpy as np

N = 5
a = np.random.rand(N, 2)
x, y = a[:,0], a[:,1]

area = 1/2 * np.sum(x*np.roll(y, 1) - y*np.roll(x, 1))

【讨论】:

    【解决方案2】:

    这里是 SQF 语言的实现:

    private _n0 = count(_polygon);
    private _surface = 0;
    
    for "_i0" from 0 to (_n0 - 1) do {
        private _p1 = _polygon select _i0;
        private _p2 = _polygon select ((_i0 + 1) % _n0);
        private _p1x = _p1 select 0;
        private _p1y = _p1 select 1;
        private _p2x = _p2 select 0;
        private _p2y = _p2 select 1;
        _surface = _surface + ((_p1x * _p2y) - (_p2x * _p1y)) / 2;
    

    你只需要用python翻译它

    【讨论】:

      【解决方案3】:

      einsum 方便实现鞋带公式

      A  # --- sample array representing a polygon ordered clockwise
      array([[  0.00,   0.00],
             [  0.00,  10.00],
             [ 10.00,  10.00],
             [ 10.00,   0.00],
             [  0.00,   0.00]])
      
      # --- can be implemented in a list comprehension of for loop
      
      def _bit_area_(a):
          """Mini e_area, used by `areas` and `centroids`."""
          x0, y1 = (a.T)[:, 1:]
          x1, y0 = (a.T)[:, :-1]
          e0 = np.einsum('...i,...i->...i', x0, y0)
          e1 = np.einsum('...i,...i->...i', x1, y1)
          return np.sum((e0 - e1) * 0.5)
          
      
      _bit_area_(A)
      100.0  # --- result for a 10 x 10 unit square,
      

      【讨论】:

        猜你喜欢
        • 2010-10-01
        • 2013-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 2013-10-24
        • 1970-01-01
        相关资源
        最近更新 更多