javaandroidopencvandroid-camera2color-detection

Efficient way to detect color using Frame Mat OpenCV Java


In order to calculate the average rgb color of a given frame, I am using the following for each loops to get the average color.

    for (int i = 0; i < pFrame.cols(); i++) {
                    for (int j = 0; j < pFrame.rows(); j++) {
                        int pixel_rgb_avg = ((int)(pFrame.get(i, j)[0] + pFrame.get(i, j)[1] + pFrame.get(i, j)[2]) / 3);
                        r_curr += pFrame.get(i, j)[0];
                        g_curr += pFrame.get(i, j)[1];
                        b_curr += pFrame.get(i, j)[2];
                        counter_curr += 1;

                    }
    }
    r_curr = r_curr/ counter_curr;
    g_curr = g_curr/ counter_curr;
    b_curr = b_curr/ counter_curr;

This works fine, but this task has to be done in realtime. Depending on the matsize it can take a long time to finish this procedure, probably caused by the get() method which is invoked three times each iteration. (It is done in a background thread)

Does anyone know a more efficient way to do this?


Solution

  • mean() returns the average value per channel and should be faster than your code.