Guide
opencv
Matrix multiplication
is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b]
with matrix B of size [b x c]
to produce matrix C of size [a x c]
.
In OpenCV it is achieved using the simple *
operator:
C = A * B // Aab * Bbc = Cac
Element-wise multiplication
is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B); // A B must have same size !!!
code
1 | cv::Mat cv_matmul(const cv::Mat& A, const cv::Mat& B) |
numpy
numpy arrays are not matrices, and the standard operations
*, +, -, /
work element-wise on arrays.
Instead, you could try using
numpy.matrix
, and*
will be treated likematrix multiplication
.
code
Element-wise multiplication
code
>>> img = np.array([1,2,3,4,5,6,7,8]).reshape(2,4)
>>> mask = np.array([1,1,1,1,0,0,0,0]).reshape(2,4)
>>> img * mask
array([[1, 2, 3, 4],
[0, 0, 0, 0]])
>>>
>>> np.multiply(img, mask)
array([[1, 2, 3, 4],
[0, 0, 0, 0]])
for
numpy.array
,*
andmultiply
work element-wise
matrix multiplication
code
>>> a = np.array([1,2,3,4,5,6,7,8]).reshape(2,4)
>>> b = np.array([1,1,1,1,0,0,0,0]).reshape(4,2)
>>> np.matmul(a,b)
array([[ 3, 3],
[11, 11]])
>>> np.dot(a,b)
array([[ 3, 3],
[11, 11]])
>>> a = np.matrix([1,2,3,4,5,6,7,8]).reshape(2,4)
>>> b = np.matrix([1,1,1,1,0,0,0,0]).reshape(4,2)
>>> a
matrix([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> b
matrix([[1, 1],
[1, 1],
[0, 0],
[0, 0]])
>>> a*b
matrix([[ 3, 3],
[11, 11]])
>>> np.matmul(a,b)
matrix([[ 3, 3],
[11, 11]])
for 2-dim,
np.dot
equalsnp.matmul
fornumpy.array
,np.matmul
meansmatrix multiplication
;
fornumpy.matrix
,*
andnp.matmul
meansmatrix multiplication
;
Reference
History
- 20190109: created.