from numba import jit
@jit(nopython=True)
def cast(mat):
mat2=empty_like(mat,uint8)
for i in range(mat.shape[0]):
for j in range(mat.shape[1]):
if mat[i,j] : mat2[i,j]=255
else : mat2[i,j]=0
return mat2
对1000x1000随机矩阵的一些测试:
In [20]: %timeit boolMatrix*uint8(255)
100 loops, best of 3: 9.46 ms per loop
In [21]: %timeit cast(boolMatrix)
1000 loops, best of 3: 1.3 ms per loop
对于调优,Cython或更简单的python用户Numba可以给您带来明显的改进:
对1000x1000随机矩阵的一些测试:
bool在numpy中隐式地强制转换为int;所以简单地用第8页(255)将完成此操作,并为您节省对数据的额外传递。你知道吗
相关问题 更多 >
编程相关推荐