Search code examples
c++opencvrgbgrayscalecolor-space

Convert BGRA pixel to grayscale


I'm trying to convert pixel (4 channels) to it's grayscale value.

Image looks like a jet colormap:

enter image description here

and I am trying to convert it to this:

enter image description here

When I'll have it converted, I want to set transparency to the original by it's grayscale value. My conversion looks like this:

uchar v = (inMat.at<cv::Vec4b>(i,j)[0]*0.07f) + 
          (inMat.at<cv::Vec4b>(i,j)[1]*0.72f) + 
          (inMat.at<cv::Vec4b>(i,j)[2]*0.21f);

I thought these values (0,07;0,72;0,21) will convert them, but it convert the pixel to something which looks more like this:

enter image description here

What values should I use to convert it right way?


Solution

  • The Jet colormap as many other colormaps, will map a greyscale value to a color, however they are not necessary related that you can convert it to greyscale and get the initial value.

    If you want to get the mapping from jet colormap to greyscale you can do the following:

    cv::Mat a(255, 1, CV_8U), b;
    for (int i = 0; i < 255; ++i)
    {
      a.at<uchar>(i) = i;
    }
    cv::applyColorMap(a,b,cv::COLORMAP_JET);
    

    Now you have like a mapping between Jet color map and the greyscale value... You just need to find the color in b and the position tells you the equivalent in a. Not sure what is the fastest way to do find the color, but maybe a mapping like from the color in hex way to the greyscale value will be good.