OpenCV: strighforward method for coloring grayscale images

What is a direct way to "colorize" an image in shades of gray. Painting, I mean transferring the values ​​of the intensity of shades of gray to one of the three channels R, G, B in the new image.

For example, 8UC1a grayscale pixel with intensity I = 50should become a color pixel 8UC3with intensity BGR = (50, 0, 0)when the image turns blue.

In Matlab, for example, what I ask for can simply be created using two lines of code:

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

But it is surprising that I can not find anything like it in OpenCV.

+5
source share
2 answers

Well, the same requires a bit more work in C ++ and 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;
}
+4

- applyColorMap OpenCV v2.4.5 Contrib. :

Color maps

+3

All Articles