为什么矩阵与灰度图像矩阵相乘会给出错误的输出?

问题描述

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

BxB

我将如何获得 print("required matrix is:\n",b) print("BxB is:\n",b*b)

解决方法

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

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

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

result[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
----------------------------------------