【问题标题】:More efficient way to map logic matrix (false/true) to uint8 matrix (0/255)?将逻辑矩阵(假/真)映射到 uint8 矩阵(0/255)的更有效方法?
【发布时间】:2016-03-28 19:57:51
【问题描述】:

我有一个布尔值的二维数组,我想将 false 映射到 0 (uint8) 并将 true 映射到 255(uint8),以便我可以将矩阵用作黑白图像。

目前我有:

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

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

【问题讨论】:

  • 我认为这是 numpy?
  • 是的。我进行了编辑以使其更清晰。
  • 和你的想法一样,但boolMatrix * np.uint8(255) 似乎更有效率。但我真的想不出更好的了。
  • 标量乘法并不是那么昂贵的过程。
  • @Reti43,在相当大的数据集上,它的速度大约快三倍

标签: python numpy type-conversion


【解决方案1】:

bool 在 numpy 中隐式转换为 int;所以简单地与 np.uint8(255) 相乘就可以解决问题,并为您节省额外的数据传递。

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-16
      • 2019-04-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多