【问题标题】:Countig points in boxes of a grid计算网格框中的点
【发布时间】:2012-06-13 22:57:44
【问题描述】:

假设有一个网格,其中包含一些点,如下图所示。 我的目标是计算网格中每框的点数。这是我的第一次尝试。

            for tupel in point_list:
               a=0
               b=0
               for i in self.boxvector:
                  if tupel[0] < i:
                     a=self.boxvector.index(i)-1
                     break

               for i in self.boxvector:
                  if tupel[1] < i:
                     b=self.boxvector.index(i)-1
                     break

               farray[a][b]+=1

它有效,但速度很慢。有没有加快速度?

我使用一个名为boxvector 的变量来定义网格。在此示例中,boxvector 为:boxvector = [-1., -.5, 0, .5, 1.]。网格始终是二次方的,最大值为 -1 和 1。 这些框通过farray 表示,看起来像farray = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]。因此,每次算法在相应的框中找到一个点时,每个框都会增加一个值。 point_list 的格式为point_list = [(x0,y0),(x1,y1),(x3,y3), ...]

感谢您的帮助!

【问题讨论】:

    标签: python


    【解决方案1】:

    看到您似乎已经在使用 matplotlib,只需使用 numpy.histogram2d

    举个例子:

    import numpy as np
    import matplotlib.pyplot as plt
    
    t = np.linspace(0, 4*np.pi, 100)
    x = np.cos(3 * t)
    y = np.sin(t)
    
    gridx = np.linspace(-1, 1, 5)
    gridy = np.linspace(-1, 1, 5)
    
    grid, _, _ = np.histogram2d(x, y, bins=[gridx, gridy])
    
    plt.figure()
    plt.plot(x, y, 'ro')
    plt.grid(True)
    
    plt.figure()
    plt.pcolormesh(gridx, gridy, grid)
    plt.plot(x, y, 'ro')
    plt.colorbar()
    
    plt.show()
    

    【讨论】:

    • 使用 np.arange,而不是 np.linspace 来获取常规网格
    【解决方案2】:

    另见

    matplotlib.nxutils.pnpoly()

    matplotlib.nxutils.points_inside_poly()

    多边形实用程序中非常快速和高效的点。您只需要根据网格角的顶点创建多边形。

    http://matplotlib.sourceforge.net/api/nxutils_api.html

    【讨论】:

      【解决方案3】:

      您可以计算位置。除以 0.5(盒子大小)。由于您的数组以 0 开头,但您的坐标以 -1 开头,因此在除法之前调整为 1。您将有 1 ( (1+1)/0.5 == 4) 的边缘情况,因此请确保它不会溢出 3。

      这是一个例子:

      >>> x,y = (0.8, -0.5)
      >>> int((x + 1) / 0.5)
      3
      >>> int((y + 1) / 0.5)
      1
      

      只要考虑得到最大结果 3。所以:

      >>> f_pos = lambda pos: min(int((pos + 1) / 0.5), 3)
      >>> f_pos(x)
      3
      >>> f_pos(y)
      1
      

      所以,完成它:

      f_pos = lambda pos: min(int((pos + 1) / 0.5), 3)
      for x,y in point_list:
          f_array[f_pos(x)][f_pos(y)] += 1
      

      【讨论】:

        猜你喜欢
        • 2018-12-13
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多