Ask Your Question

Mat per-element operation: vector-matrix multiplication

asked 2013-04-03 03:50:48 -0500

Nesbit gravatar image

updated 2014-10-22 21:47:13 -0500

aledalgrande gravatar image

I is an mxn matrix and each element of I is a 1x3 vector (I is a 3-channel Mat image actually).

M is a 3x3 matrix.

J is an matrix having the same dimension as I and is computed as follows: each element of J is the vector-matrix product of the corresponding (i.e. having the same coordinates) element of I and M.

I.e. if v1(r1,g1,b1) is an element of I and v2(r2,g2,b2) is its corresponding element of J, then v2 = v1 * M (this is a vector-matrix product, not a per-element product).

Question: How to compute J efficiently (in terms of speed)?

Thank you for your help.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2013-04-03 04:03:03 -0500

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;

Bitwise 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);

I guess this answers your problem? The * operator on Mat is defined to do what you want.

source :

edit flag offensive delete link more


Thanks. But that's not what I was searching for. Maybe I was not clear enough.

What I want to do is to multiply every element (that is a 3-component vector) of a matrix with a given 3x3 matrix.

for(int i=0;i<I.cols;i++) 
    for(int j=0;j<I.rows;j++) 
            I(j,i) = I(j,i)*M; 
Nesbit gravatar imageNesbit ( 2013-04-03 05:00:45 -0500 )edit

Then you need a for loop, looping over the elements of the first matrix, tha

StevenPuttemans gravatar imageStevenPuttemans ( 2013-04-03 05:04:54 -0500 )edit

I would like just to remind that my question is not how to do that, but how to do that efficiently (in terms of speed).

Nesbit gravatar imageNesbit ( 2013-04-03 07:04:32 -0500 )edit

I know, but I have searched multiple times at how to traverse the Mat element efficiently, havent found any solution yet, so interested to hear if you do.

StevenPuttemans gravatar imageStevenPuttemans ( 2013-04-03 07:18:20 -0500 )edit

That is called the Kronecker product and it's not supported by OpenCV, so you have to write your own.

aledalgrande gravatar imagealedalgrande ( 2014-10-22 21:46:01 -0500 )edit

Question Tools

1 follower


Asked: 2013-04-03 03:50:48 -0500

Seen: 21,052 times

Last updated: Apr 03 '13