开发者社区> 问答> 正文

使用NumPy的两个矩形的交集

我具有以下功能来找到两个矩形的交点。它有点慢,我不知道这是由于OR条件还是>,<运算符引起的。我想知道是否有一种方法可以提高is_intersect()函数的性能。也许和NumPy在一起?还是Cython?

import numpy as np

def is_intersect(rect1, rect2):
    xmin1, xmax1, ymin1, ymax1 = rect1
    xmin2, xmax2, ymin2, ymax2 = rect2
    if xmin1 > xmax2 or xmax1 < xmin2:
        return False
    if ymin1 > ymax2 or ymax1 < ymax2:
        return False
    return True

N_ELEMS = 100000000
rects1 = np.random.rand(N_ELEMS,4)
rects2 = np.random.rand(N_ELEMS,4)

temp_dct = dict()

for i in range(N_ELEMS):
    rect1 = rects1[i,:]
    rect2 = rects2[i,:]
    if is_intersect(rect1, rect2):
        temp_dct[i] = True

我不能从缓存结果中获利,因为这些点将是增量的,也就是说,一个矩形将在空间中移动(永远不会在同一位置)。在此示例中,我使用了NumPy的random()函数,但实际使用情况并非如此。我将调用is_intersect()函数100000000次或更多次。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 17:13:42 552 0
1 条回答
写回答
取消 提交回答
  • 您可以通过使用向量化比较和np.any避免for循环来提高性能:

    result = (1 - np.any([rects1[:,0] > rects2[:,1], 
                          rects1[:,1] < rects2[:,0], 
                          rects1[:,2] > rects2[:,3], 
                          rects1[:,3] < rects2[:,2]], 
                         axis=0)).astype(bool)
    

    您没有字典,但是可以按索引访问result

    1亿个元素的性能:

    import numpy as np
    import timeit
    
    N_ELEMS = 100_000_000
    rects1 = np.random.rand(N_ELEMS,4)
    rects2 = np.random.rand(N_ELEMS,4)
    
    start_time = timeit.default_timer()
    result = (1 - np.any([rects1[:,0] > rects2[:,1], 
                          rects1[:,1] < rects2[:,0], 
                          rects1[:,2] > rects2[:,3], 
                          rects1[:,3] < rects2[:,2]], 
                         axis=0)).astype(bool)
    
    print(timeit.default_timer() - start_time)
    2.9162093999999996
    

    回答来源:stackoverflow

    2020-03-23 17:13:50
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载