Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV: A straighforward method of colorizing a grayscale image

Tags:

c++

opencv

What is a straight forward method of "colorizing" a grayscale image. By colorizing, I mean porting the grayscale intensity values to one of the three R, G, B channels in a new image.

For example a 8UC1 grayscale pixel with intensity of I = 50 should become a 8UC3 color pixel of intensity BGR = (50, 0, 0) when the picture is colorized to "blue".

In Matlab for example, what I'm asking for can be simply created with two lines of code:

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

But amazingly I cannot find anything similar in OpenCV.

like image 440
Bee Avatar asked Apr 05 '13 20:04

Bee


People also ask

How image colorization works?

Image colorization is the process of taking an input grayscale (black and white) image and then producing an output colorized image that represents the semantic colors and tones of the input (for example, an ocean on a clear sunny day must be plausibly “blue” — it can't be colored “hot pink” by the model).


1 Answers

Well, the same thing 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);

or as a function (compacted):

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;
}
like image 173
Niko Avatar answered Sep 30 '22 20:09

Niko