Search code examples
androidopencvimage-processingcolorspixel

OpenCV convert color per pixel


Hello i want to convert the color in image, i'm using per-pixel methods but it seems very slow

src.getPixels(pixels, 0, width, 0, 0, width, height);

        // RGB values
        int R;

        for (int i = 0; i < pixels.length; i++) {
            // Get RGB values as ints


            // Set pixel color
            pixels[i] = color;

        }

        // Set pixels
        src.setPixels(pixels, 0, width, 0, 0, width, height);

my question, is there any way i can do it using openCV? change pixel to the color i want ?


Solution

  • I recommend this excellent article on how to access/modify an opencv image buffer. I recommend "the efficient way":

     int i,j;
        uchar* p;
        for( i = 0; i < nRows; ++i)
        {
            p = I.ptr<uchar>(i);
            for ( j = 0; j < nCols; ++j)
            {
                p[j] = table[p[j]];
            }
    

    Or "the iterator-safe method":

    MatIterator_<Vec3b> it, end;
    for( it = I.begin<Vec3b>(), end = I.end<Vec3b>(); it != end; ++it)
    {
       (*it)[0] = table[(*it)[0]];
       (*it)[1] = table[(*it)[1]];
       (*it)[2] = table[(*it)[2]];
    }
    

    For further optimizations, using cv::LUT() (where possible) can give huge speedups, but it is more intensive to design/code.