Bootstrap

OpencvForAndroid记录——get()和put()函数

最近写这块代码的性能优化。

public static Mat array2Mat(double[][][] data) {

        int height = data.length;
        int width = data[0].length;
        Mat mat = new Mat(height, width, CvType.CV_8UC3);
        double[] mat_data = new double[width * height * 3];

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                mat_data[i * width * 3 + j * 3] = data[i][j][0];
                mat_data[i * width * 3 + j * 3 + 1] = data[i][j][1];
                mat_data[i * width * 3 + j * 3 + 2] = data[i][j][2];
            }
        }
        mat.put(0, 0, mat_data);
        return mat;
        /*int height = data.length;
        int width = data[0].length;
        Mat mat = new Mat(height, width, CvType.CV_8UC3);

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                mat.put(i, j, data[i][j]);
            }
        }
        return mat;*/
    }

上面代码明显比下面代码快,不止一倍。
同样,get函数也是如此;

    public static double[][][] matGray2Array(Mat mat) {

        int width = mat.cols();
        int height = mat.rows();
        double[][][] data = new double[height][width][1];
        byte[] grayData = new byte[height * width];
        mat.get(0, 0, grayData);
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                data[i][j][0] = grayData[(i * width + j)];
                data[i][j][0] = data[i][j][0] >= 0 ? data[i][j][0] : data[i][j][0] + 256;
//                data[i][j] = mat.get(i, j);
            }
        }
        return data;
    }

注:byte的范围是-128到127,取的时候是按照byte取,放的时候按照double放;
调试发现,-128到-1的Byte数据转换到double数据,需要映射到128到255(double取的时候整体范围是0到255)。

;