【问题标题】:OpenCV: A straighforward method of colorizing a grayscale imageOpenCV:一种为灰度图像着色的简单方法
【发布时间】:2015-08-14 09:00:24
【问题描述】:

什么是“着色”灰度图像的直接方法。通过着色,我的意思是将灰度强度值移植到新图像中的三个 R、G、B 通道之一。

例如,当图片被着色为“蓝色”时,强度为I = 508UC1 灰度像素应该变成强度为BGR = (50, 0, 0)8UC3 彩色像素。

例如,在 Matlab 中,我所要求的可以简单地用两行代码创建:

color_im = zeros([size(gray_im) 3], class(gray_im));
color_im(:, :, 3) = gray_im; 

但令人惊讶的是,我在 OpenCV 中找不到类似的东西。

【问题讨论】:

    标签: c++ opencv


    【解决方案1】:

    嗯,同样的事情需要在 C++ 和 OpenCV 中做更多的工作:

    // Load a single-channel grayscale image
    cv::Mat gray = cv::imread("filename.ext", CV_LOAD_IMAGE_GRAYSCALE);
    
    // Create an empty matrix of the same size (for the two empty channels)
    cv::Mat empty = cv::Mat::zeros(gray.size(), CV_8UC1);
    
    // Create a vector containing the channels of the new colored image
    std::vector<cv::Mat> channels;
    
    channels.push_back(gray);   // 1st channel
    channels.push_back(empty);  // 2nd channel
    channels.push_back(empty);  // 3rd channel
    
    // Construct a new 3-channel image of the same size and depth
    cv::Mat color;
    cv::merge(channels, color);
    

    或作为函数(压缩):

    cv::Mat colorize(cv::Mat gray, unsigned int channel = 0)
    {
        CV_Assert(gray.channels() == 1 && channel <= 2);
    
        cv::Mat empty = cv::Mat::zeros(gray.size(), gray.depth());
        std::vector<cv::Mat> channels(3, empty);
        channels.at(channel) = gray;
    
        cv::Mat color;
        cv::merge(channels, color);
        return color;
    }
    

    【讨论】:

    • 有趣的是,就在我提出这个问题之后,我发现了cv::merge() 函数和cv::Matvector,并做了与你在这里所做的完全相同的事情。谢谢。
    【解决方案2】:

    contrib 模块中有special function to do this - applyColorMap 来自 v2.4.5 的 OpenCV。有不同的颜色图可供选择:

    【讨论】:

    • 我不明白这应该如何帮助实现所需的输出?显然,无法定义自定义颜色图。
    猜你喜欢
    • 2012-05-28
    • 2011-11-23
    • 1970-01-01
    • 2017-07-31
    • 2010-12-22
    • 2023-02-22
    • 2014-10-14
    • 2023-03-26
    相关资源
    最近更新 更多