Search code examples
javaopencvoptimizationcolorslag

Algorithm RGB to Gray Lagging


Trying to implements the conversion method that converts a picture from RGB to Gray. When i use my method and display the rendering in an ImageView , it's lags so much and when i use the cvtColor, function from the library OpenCV it works like a charm. Can anyone explain me where is the problem ? here's my method:

public void RGBToGray(Mat m){
    for(int i = 0; i < m.rows(); i++){
        for(int j = 0; j < m.cols(); j++){
            double[] pix = m.get(i, j);
            pix[0] = pix[1] = pix[2] = (0.21)*pix[0]+(0.72)*pix[1]+(0.07)*pix[2];
            m.put(i, j, pix);
        }
    }
}

Solution

  • Here's the solution for those who will see the post according to Dan Masek comment:

    public static void RGBToGray2(Mat m){
        ArrayList<Mat> sousMatrices = new ArrayList<Mat>();
        Core.split(m, sousMatrices);
        Mat result = new Mat();
        Core.addWeighted(sousMatrices.get(0), 0.21, sousMatrices.get(1), 0.72, 0, result);
        Core.addWeighted(sousMatrices.get(2), 0.07, result, 1 ,0 , result);
        sousMatrices.set(0,result);
        sousMatrices.set(1,result);
        sousMatrices.set(2,result);
        Core.merge(sousMatrices, m);
    }