Reputation: 3
I have two 2 x 2 matrices and I want to get the tensor product of them using opencv, for example:
{
{0, 1},
{1, 0}
}
x
{
{1, 0},
{0, 1}
}
=
{
{0, 0, 1, 0},
{0, 0, 0, 1},
{1, 0, 0, 0},
{0, 1, 0, 0}
}
So I have something like:
cv::Mat mat1 = (cv::Mat_<double>(2,2) << 1, 0, 0, 1);
cv::Mat mat2 = (cv::Mat_<double>(2,2) << 0, 1, 1, 0);
is there some tensor product function built into opencv to get the result I require?
Upvotes: 0
Views: 1382
Reputation: 41775
OpenCV doesn't provide builtin operations on tensors. You need to rely on other libraries for that.
However, I'm no expert in tensors, but this looks like a Kronecker product to me (still no available in OpenCV). If so, you can find an implementation here that I report also in the code below, that produces the result you require:
[0, 1;
1, 0]
x
[1, 0;
0, 1]
=
[0, 0, 1, 0;
0, 0, 0, 1;
1, 0, 0, 0;
0, 1, 0, 0]
Code:
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
Mat kron(const Mat& A, const Mat& B)
{
CV_Assert(A.channels() == 1 && B.channels() == 1);
Mat1d Ad, Bd;
A.convertTo(Ad, CV_64F);
B.convertTo(Bd, CV_64F);
Mat1d Kd(Ad.rows * Bd.rows, Ad.cols * Bd.cols, 0.0);
for (int ra = 0; ra < Ad.rows; ++ra)
{
for (int ca = 0; ca < Ad.cols; ++ca)
{
Kd(Range(ra*Bd.rows, (ra + 1)*Bd.rows), Range(ca*Bd.cols, (ca + 1)*Bd.cols)) = Bd.mul(Ad(ra, ca));
}
}
Mat K;
Kd.convertTo(K, A.type());
return K;
}
int main(int argc, char **argv)
{
Mat mat1 = (Mat_<double>(2, 2) << 0, 1, 1, 0);
Mat mat2 = (Mat_<double>(2, 2) << 1, 0, 0, 1);
Mat res = kron(mat1, mat2);
cout << mat1 << endl << endl;
cout << " x " << endl << endl;
cout << mat2 << endl << endl;
cout << " = " << endl << endl;
cout << res << endl;
return 0;
}
Upvotes: 1