如何加速python循环?

2024-05-21 13:42:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我从while循环调用这个函数'detection_bbox'

def search_layer(detection):
    center_x, center_y, w, h = (detection[0:4] * np.array([width, height, width, height])).astype('int')
    x = int(center_x - w / 2)
    y = int(center_y - h / 2)
    return [x, y, int(w), int(h)]

def detection_bbox(layer_outputs):
    b_boxes = []
    for l_output in layer_outputs:
        b_boxes.extend([search_layer(detect) for detect in l_output if detect[5] > 0.5])
    return b_boxes

我试着在1.2GHz的CPU上运行它。l_输出大约有5000个元素,因此它大大降低了我的应用程序的速度。我怎样才能加快速度


Tags: layerforoutputsearchreturndefwidthoutputs
1条回答
网友
1楼 · 发布于 2024-05-21 13:42:10

search_layer必须是您的瓶颈,因为其他一切都应该非常快,所以:

  1. 优化search_layer
  2. 只为那些detect[5]>0的元素调用search_layer-减少搜索空间并
  3. 对于这些元素,只运行search_layer一次
def detection_bbox(layer_outputs):

    b_boxes = []
    valid_outputs = [l for l in layer_outputs if l[5] > 0]

    for output in valid_outputs:
        detect = search_layer(output)
        if detect:
            b_boxes.extend(detect)

    return b_boxes

相关问题 更多 >