给定边界框创建遮罩

时间:2020-07-23 13:34:00

标签: python-3.x numpy

arr = []
j =0 
for img in train['image_id'].unique():
    bbox = train[train['image_id'] == img]   #bbox[0] = x ,similarly others 
    template = np.zeros((1024,1024))
    j+=1
    for i in train.itertuples():
        template[i._6:i._6 + i._8  ,  i._7:i._7 + i._9] = 1 
    arr.append(template)

此处i._6,i._8,i._7,i._9 是边界框的值
有没有办法使此代码快速

2 个答案:

答案 0 :(得分:1)

使用numpy时,可以使用numba's JIT compiler来获得一些速度上的提升。

from numba import jit

@jit
def myfunction()..

这将compile您的代码并将其缓存,因此第一次调用可能会更快,而随后对该函数的调用可能会极其快。

但是,您还应该调查代码中实际减速的地方,并尝试对其进行改进。

这通过cProfile被称为profiling, and can be done with the standard libraries(也存在更​​专业的第三方软件包)

SnakeVizcProfile

输出文件的简单查看器
python -m cProfile -o program.profile my_program.py
snakeviz program.profile

您可能会看到速度改进,并尽可能将tuples等价物替换为Python结构(例如fornumpy循环)。

答案 1 :(得分:0)

我用opencv达到了类似的效果

for img in train['image_id'].unique():
    bbox = train[train['image_id'] == img]
    template = np.zeros((1024,1024))
    for i in bbox.itertuples():
        cv2.rectangle(template , (i._6 , i._7) , (i._6 + i._8  , i._7 + i._9)  , (255,255,255) ,-1)
    
    cv2.imwrite('masked/'+img+'.jpg',template)