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.
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).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With