Reputation: 5764
I got a 3x3 matrix in OpenCV format (org.opencv.core.Mat) that I want to copy into android.graphics.Matrix. Any idea how?
[EDIT]
Here's the final version as inspired by @elmiguelao. The source matrix is from OpenCV and the destination matrix is from Android.
static void transformMatrix(Mat src, Matrix dst) {
int columns = src.cols();
int rows = src.rows();
float[] values = new float[columns * rows];
int index = 0;
for (int x = 0; x < columns; x++)
for (int y = 0; y < rows; y++) {
double[] value = src.get(x, y);
values[index] = (float) value[0];
index++;
}
dst.setValues(values);
}
Upvotes: 0
Views: 1472
Reputation: 5007
This function also respects the Mat
's data type (float or double):
static Matrix cvMat2Matrix(Mat source) {
if (source == null || source.empty()) {
return null;
}
float[] matrixValuesF = new float[source.cols()*source.rows()];
if (CvType.depth(source.type()) == CvType.CV_32F) {
source.get(0,0, matrixValuesF);
} else {
double[] matrixValuesD = new double[matrixValuesF.length];
source.get(0, 0, matrixValuesD);
//will throw an java.lang.UnsupportedOperationException if type is not CvType.CV_64F
for (int i=0; i<matrixValuesD.length; i++) {
matrixValuesF[i] = (float) matrixValuesD[i];
}
}
Matrix result = new Matrix();
result.setValues(matrixValuesF);
return result;
}
Upvotes: 1
Reputation: 812
Something along these lines:
cv.Mat opencv_matrix;
Matrix android_matrix;
if (opencv_matrix.isContiguous()) {
android_matrix.setValues(cv.MatOfFloat(opencv_matrix.ptr()).toArray());
} else {
float[] opencv_matrix_values = new float[9];
// Undocumented .get(row, col, float[]), but seems to be bulk-copy.
opencv_matrix.get(0, 0, opencv_matrix_values);
android_matrix.setValues(opencv_matrix_values);
}
Upvotes: 2