spiderman
spiderman

Reputation: 13

Convert grayscale image to single color in OpenCV

I'm wondering if there is a way to convert a grayscale image to one color image? Like if I have an image in grayscale and I want to convert it to shades of blue instead? Is that possible in OpenCV?

Thank you very much!

Upvotes: 1

Views: 2478

Answers (3)

Chunho
Chunho

Reputation: 36

According to the opencv community answer, you should of creating a 3-channel image by yourself.

   Mat empty_image = Mat::zeros(src.rows, src.cols, CV_8UC1);//initial empty layer
   Mat result_blue(src.rows, src.cols, CV_8UC3);                 //initial blue result

   Mat in1[] = { ***GRAYINPUT***, empty_image, empty_image };    //construct 3 layer Matrix
   int from_to1[] = { 0,0, 1,1, 2,2 };
   mixChannels( in1, 3, &result_blue, 1, from_to1, 3 );          //combine image

After that, you can get your blue channel image. Normally, the blue channel of an colour image in opencv is the first layer (cuz they put 3 channels as BGR).

By the way, if you wanna use the copy each pixel method, you can initial an empty image

   Mat result_blue(src.rows, src.cols, CV_8UC3); //blue result
   for (int i =0; i<src.rows; i++)
        for (int j=0; j<src.cols; j++){
               Vec3b temp = result_blue.at<Vec3b>(Point(i,j));//get each pixel
               temp[0] = gray.at<uchar>(i,j);                 //give value to blue channel
               result_blue.at<Vec3b>(Point(x,y)) = temp;      //copy back to img
        }

However, it will take longer as there are two loops!

Upvotes: 1

JackKalish
JackKalish

Reputation: 1585

To accomplish this you would essentially just need to iterate over all the pixels in the grayscale image and map the values over to a color range. Here is pseudo-code:

grayImage:imageObject;
tintedImage:imageObject;

//Define your color tint here
myColorR:Int = 115;
myColorG:Int = 186;
myColorB:Int = 241;

for(int i=0; i<imagePixelArray.length; i++){
   float pixelBrightness = grayImage.getPixelValueAt(i)/255;
   int pixelColorR = myColorR*pixelBrightness;
   int pixelColorG = myColorG*pixelBrightness;
   int pixelColorB = myColorB*pixelBrightness;
   tintedImage.setPixelColorAt(i, pixelColorR, pixelColorG, pixelColorB);
}

Hope that helps!

Upvotes: 1

Anton Savelyev
Anton Savelyev

Reputation: 762

A gray scale image is usually just one dimensional. Usually what I do if I want to pass in a gray scale image into a function that accepts RGB (3-dimensional), I replicate the the matrix 3 times to create a MxNx3 matrix. If you wish to only use the Blue channel, just concat MxN of zeros in the 1st dimension and the 2nd dimension while putting the original gray scale values in the 3rd dimension.

Upvotes: 1

Related Questions