将3x3 OpenCV Mat转换为Android Matrix

时间:2014-02-14 16:07:26

标签: java android opencv matrix

我得到了一个OpenCV格式的3x3矩阵(org.opencv.core.Mat),我要将其复制到android.graphics.Matrix中。知道怎么样?

[编辑]

这是@elmiguelao启发的最终版本。源矩阵来自OpenCV,目标矩阵来自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);
}

2 个答案:

答案 0 :(得分:2)

这些方面的东西:

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

答案 1 :(得分:0)

此函数还尊重Mat的数据类型(float或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;
}