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

时间:2015-09-16 04:24:06

标签: c++ opencv image-processing

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

2 个答案:

答案 0 :(得分: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;
    }

然后我设置了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);

之后:将输入转换为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);

给我这个输入的输出:

enter image description here

enter image description here

在评论中,您希望将“黑色”替换为“红色”。你必须用“黑色”来定义你的意思。理论上,黑色是intensity = 0,一切都是&gt; 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;

例如给出这个结果:

enter image description here

答案 1 :(得分:2)

这里有一个小测试代码(密钥为inRange):

  1. 在灰色图像中创建一个矩形(值为25)
  2. 创建一个掩码,其中25个值为(inRange
  3. 将灰色图像转换为彩色图像
  4. 更改蒙版

    的像素值
    cv::Mat image = cv::Mat::zeros(cv::Size(200,200), CV_8U); //create zero image
    cv::rectangle(image, cv::Rect(50, 50, 100, 100), cv::Scalar::all(25), -1); //write a rectangle
    cv::imshow("image", image); //show image
    cv::Mat mask;
    cv::inRange(image,25,25,mask); //mask the 25 values
    cv::cvtColor(image, image, CV_GRAY2BGR); //convert gray image to BGR
    cv::Scalar red(0,0,255); 
    image.setTo(red,mask); //change all 25 values into red color
    cv::imshow("colorImage", image); //show result image
    cv::waitKey(0); //wait until you press a key