Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV: How to calculate max(R,G,B)

Tags:

c++

image

opencv

Sadly the OpenCV documentation has been written for mathematicians only or for those who already know how to use OpenCV.

I want to do such a simple thing as getting the highest value of R,G,B for each pixel and write it to a new gray scale image. I tried merge(), split() and others but without success.

The following function does exactly what I want, but I wonder if OpenCV could do that simpler.

Mat CalcRGBmax(Mat i_RGB)
{
    if (i_RGB.channels() != 3)
        throw "24 bit color image expected.";

    Mat i_Gray(i_RGB.rows, i_RGB.cols, CV_8UC1);

    for (int Y=0; Y<i_RGB.rows; Y++)
    {
        BYTE* pu8_Src = i_RGB. ptr<BYTE>(Y);
        BYTE* pu8_Dst = i_Gray.ptr<BYTE>(Y);

        int P = 0;
        for (int X=0; X<i_RGB.cols; X++)
        {         
            BYTE B = pu8_Src[P++];
            BYTE G = pu8_Src[P++];
            BYTE R = pu8_Src[P++];

            pu8_Dst[X] = max(R, max(G,B));
        }
    }
    return i_Gray;
}
like image 238
Elmue Avatar asked Jul 10 '14 21:07

Elmue


1 Answers

Your code will be much faster than this, but this is how to do it with split() and max():

Mat CalcRGBmax(Mat i_RGB)
{
    std::vector<cv::Mat> planes(3);
    cv::split(i_RGB, planes);
    return cv::Mat(cv::max(planes[2], cv::max(planes[1], planes[0])));
}
like image 195
Bull Avatar answered Oct 13 '22 02:10

Bull