【问题标题】:Why is matrix multiplication with grayscale image matrix giving wrong output?为什么矩阵乘法与灰度图像矩阵会给出错误的输出?
【发布时间】:2021-04-28 15:40:47
【问题描述】:

我在 Colab 上使用 cv2.imread() 加载了一张图像,并将其转换为一些灰度图像。我有一个矩阵B,它是从同一张灰度图像中提取的。但是当我试图将它自身相乘时,即当我评估B@B 时,输出将是一个矩阵,但它的条目与我们乘以BxB 时得到的不同:

print("Required matrix is:\n", b)
print("BxB is:\n", b*b)

我将如何获得BxB

【问题讨论】:

    标签: python opencv matrix-multiplication grayscale


    【解决方案1】:

    对于 NumPy 数组,* 运算符执行逐元素乘法:

    result[0, 0] = b[0, 0] * b[0, 0]
    

    在你的情况下,你很可能有dtype=np.uint8,这样你就会遇到整数溢出,例如:

    result[0, 0] = b[0, 0] * b[0, 0] = 234 * 234 = 54576
    

    由于np.uint8 被限制在[0, ..., 255] 的值范围内,您需要获取54576 % 256 = 228,即您的result[0, 0]

    因此,如果您确实希望在不发生整数溢出的情况下进行逐元素乘法,例如,将b 转换为np.int

    或者,如果您真的想要进行实数矩阵乘法,也可以将b 转换为np.int,但也要使用正确的@ 运算符。

    以下是不同用例的一些代码:

    import numpy as np
    
    b = np.array([[234, 229], [129, 11]], np.uint8)
    
    print('Matrix b:\n', b, '\n')
    # Matrix b:
    #  [[234 229]
    #  [129  11]] 
    
    print('Element-wise multiplication b * b (np.uint8):\n',
          b * b, '\n')
    # Element-wise multiplication b * b (np.uint8):
    #  [[228 217]
    #  [  1 121]] 
    
    print('Element-wise multiplication b * b (np.int):\n',
          np.int_(b) * np.int_(b), '\n')
    # Element-wise multiplication b * b (np.int):
    #  [[54756 52441]
    #  [16641   121]] 
    
    print('Element-wise multiplication b * b (np.int) % 256:\n',
          (np.int_(b) * np.int_(b)) % 256, '\n')
    # Element-wise multiplication b * b (np.int) % 256:
    #  [[228 217]
    #  [  1 121]] 
    
    print('Actual matrix multiplication b @ b (np.int):\n',
          (np.int_(b) @ np.int_(b)), '\n')
    # Actual matrix multiplication b @ b (np.int):
    #  [[84297 56105]
    #  [31605 29662]] 
    
    ----------------------------------------
    System information
    ----------------------------------------
    Platform:      Windows-10-10.0.16299-SP0
    Python:        3.9.1
    PyCharm:       2021.1.1
    NumPy:         1.20.2
    ----------------------------------------
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 2021-10-28
    • 2015-01-12
    • 2022-07-21
    相关资源
    最近更新 更多