首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >[python]numba安装后测试代码

[python]numba安装后测试代码

作者头像
git clone firc-dataset
发布2025-07-17 19:18:42
发布2025-07-17 19:18:42
2340
举报
应用和对比

​主要任务是有两组bboxs,进行匹配,计算iou阈值,如果直接用for循环,需要写两个for循环,时间复杂度还是很大的 因此尝试使用numba对循环进行加速,具体代码如下:

代码语言:javascript
复制
from numba import jit
import numpy as np
from scipy.spatial import KDTree
import time
from tqdm import tqdm

# 计算iou
@jit(nopython=True)
def bbox_iou(box1, box2):
    x1, y1, x2, y2 = box1
    x1_, y1_, x2_, y2_ = box2

    inter_x1 = max(x1, x1_)
    inter_y1 = max(y1, y1_)
    inter_x2 = min(x2, x2_)
    inter_y2 = min(y2, y2_)
    inter_w = max(0, inter_x2 - inter_x1)
    inter_h = max(0, inter_y2 - inter_y1)

    union = (x2 - x1) * (y2 - y1) + (x2_ - x1_) * (y2_ - y1_) - inter_w * inter_h
    iou = inter_w * inter_h / union
    return iou

# 定义两组bbox
bbox1 = np.random.rand(1000, 4)
bbox2 = np.random.rand(500, 4)

# 利用for循环计算匹配
start_time = time.time()
matches = []
for i in tqdm(range(bbox1.shape[0])):
    max_iou = 0
    match_idx = -1
    for j in range(bbox2.shape[0]):
        iou = bbox_iou(bbox1[i], bbox2[j])
        if iou > max_iou:
            max_iou = iou
            match_idx = j
    matches.append(match_idx)
print("Matching with for loop takes: %.3f s" % (time.time() - start_time))
@jit(nopython=True)   # 
def match_loop(bbox1,bbox2):
    matches = []
    for i in range(bbox1.shape[0]):
        max_iou = 0
        match_idx = -1
        for j in range(bbox2.shape[0]):
            iou = bbox_iou(bbox1[i], bbox2[j])
            if iou > max_iou:
                max_iou = iou
                match_idx = j
        matches.append(match_idx)

start_time = time.time()
match_loop(bbox1,bbox2)
print("Matching with for loop takes: %.3f s" % (time.time() - start_time))

需要注意的是: numba加速的函数,即@jit()修饰的函数内,如果调用了其他函数,那么这个函数也应该被@jit()修饰,比如bbox_iou()这个函数,也应该被@jit()修饰。原来的tqdm()就不能出现在函数内部了,不然会报错

对比结果:

Matching with for loop takes: 0.312 s Matching with for loop takes: 0.1537 s 第一个是for循环计算的结果,第二个是numba加速后的结果,确实加速了很多,很不错

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-03-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 应用和对比
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档