Chaitanya Krish
Chaitanya Krish

Reputation: 65

Drawing a colored rectangle in a grayscale image using opencv

Is it possible to draw a colored rectangle in a grayscale image using opencv. I tried several ways but either the whole image turns grayscale or RGB.

Upvotes: 5

Views: 16664

Answers (2)

Miki
Miki

Reputation: 41765

You can't have a mixed gray and color image. You can have a look at Is there a way to have both grayscale and rgb pixels on the same image opencv C++?.

So you can't draw a colored rectangle on a grayscale CV_8UC1 image. But you can draw it on a CV_8UC3 image that shows your gray image.

You can create a CV_8UC3 gray-colored image with cvtColor(..., ..., COLOR_GRAY2BGR), and then you can draw your colored rectangle on it, e.g:

enter image description here

Note that this image, however, is no more of type CV_8UC1, but CV_8UC3 instead.

#include <opencv2/opencv.hpp>
using namespace cv;

int main()
{
    Mat1b gray = imread("path_to_image", IMREAD_GRAYSCALE);

    // Convert gray image to BGR
    Mat3b grayBGR;
    cvtColor(gray, grayBGR, COLOR_GRAY2BGR);

    // Draw the colored rectangle
    rectangle(grayBGR, Rect(10, 10, 100, 200), Scalar(0,255,0), 2);

    imshow("Image with Rect", grayBGR);
    waitKey();

    return 0;
}

Upvotes: 9

Malcolm McLean
Malcolm McLean

Reputation: 6404

I doubt it. A grayscale image will be stored internally as one channel per pixel. What you must do is convert the image to colour (using red = green = blue = grey value). Then you can draw any colour into the grey background. But of course the entire image then becomes a colour image, it's very unlikely there's any support for greyscale images with small areas of colour.

Upvotes: 1

Related Questions