用开放式cv替换rgb颜色的灰度颜色

abh*_*312 0 c++ opencv image-processing

我想用每个像素的rgb颜色替换灰度颜色.我是新手,打开简历.
GrayScale val = 25替换为rgb值= 0,0,255

Mic*_*cka 6

这是如何使用LUT:

我用灰度值创建了一些虚拟图像:

cv::Mat input = cv::Mat(512,512,CV_8UC1, cv::Scalar(0));
for(int j=0; j<input.rows; ++j)
    for(int i=0; i<input.cols; ++i)
    {
        input.at<unsigned char>(j,i) = i/2;
    }
Run Code Online (Sandbox Code Playgroud)

然后我设置了LUT:

// create replacement look-up-table:
// 1. basic => gray values of given intensity
cv::Mat lookUpTable(1, 256, CV_8UC3);

for( int i = 0; i < 256; ++i)
    lookUpTable.at<cv::Vec3b>(0,i) = cv::Vec3b(i,i,i);

// 2. replace whatever colors you want:
lookUpTable.at<cv::Vec3b>(0,25) = cv::Vec3b(25,0,0);

lookUpTable.at<cv::Vec3b>(0,100) = cv::Vec3b(0,255,0); // means to replace each gray == (100) value by a (0,255,0) color value after LUT call
lookUpTable.at<cv::Vec3b>(0,115) = cv::Vec3b(255,0,0);
lookUpTable.at<cv::Vec3b>(0,200) = cv::Vec3b(0,100,255);
Run Code Online (Sandbox Code Playgroud)

之后:将输入转换为COLOR并调用LUT:

// unfortunately, we have to convert to color, because OpenCV doesnt allow LUT from single channel to 3 channel directly. (LUT must have same number of channels as input)
cv::Mat input_3channels;
cv::cvtColor(input, input_3channels, CV_GRAY2BGR);

cv::Mat output;
cv::LUT(input_3channels, lookUpTable, output);
Run Code Online (Sandbox Code Playgroud)

给我这个输入的输出:

在此输入图像描述

在此输入图像描述

在您的评论中,您希望将"黑色"替换为"红色".你必须用"黑色"来定义你的意思.理论上,黑色是,intensity = 0而0>只是一个非常深的灰色.所以这里我展示了如何将一些范围设置为颜色:

cv::Mat lookUpTable(1, 256, CV_8UC3);

for( int i = 0; i < 256; ++i)
    lookUpTable.at<cv::Vec3b>(0,i) = cv::Vec3b(i,i,i);

// 2. replace "black color" by red:
// you have to define what black means. If you mean pure black (intensity == 0) then use this:
//lookUpTable.at<cv::Vec3b>(0,0 /* intensity == 0 */) = cv::Vec3b(0,0,255);

// if you mean something that appears mostly black for a human eye, use something like this:
unsigned char startIntensity = 0; // start at intensity 0 (black)
unsigned char endIntensity = 20; // the higher this value, the more "dark grey" will be replaced by red too
cv::Vec3b replacementColor = cv::Vec3b(0,0,255); // red
for(int i=startIntensity ; i < endIntensity ; ++i)
    lookUpTable.at<cv::Vec3b>(0,i) = replacementColor;
Run Code Online (Sandbox Code Playgroud)

例如给出这个结果:

在此输入图像描述