将逻辑矩阵(假/真)映射到uint8矩阵(0/255)的更有效方法?

2024-09-29 19:24:50 发布

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

我有一个布尔值的二维数组,我想将false映射为0(uint8),将true映射为255(uint8),这样我就可以将矩阵用作黑白图像。你知道吗

目前我有:

uint8matrix = boolMatrix.astype(numpy.uint8)*255

但我认为乘法增加了不必要的计算。你知道吗


Tags: 图像numpyfalsetrue矩阵数组乘法astype
2条回答

对于调优,Cython或更简单的python用户Numba可以给您带来明显的改进:

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

bool在numpy中隐式地强制转换为int;所以简单地用第8页(255)将完成此操作,并为您节省对数据的额外传递。你知道吗

相关问题 更多 >

    热门问题