openCV - draw color contours on greyscale image

28,513

You need a 3-channel (RGB) image in order to draw and display colors. Your Mat_<uchar> matrix is only one channel. You can convert your grayscale image to a color image as follows:

  // read image
  cv::Mat img_gray = imread(path,0);

  // create 8bit color image. IMPORTANT: initialize image otherwise it will result in 32F
  cv::Mat img_rgb(img_gray.size(), CV_8UC3);

  // convert grayscale to color image
  cv::cvtColor(img_gray, img_rgb, CV_GRAY2RGB);
Share:
28,513
alvinleetya
Author by

alvinleetya

Updated on April 09, 2020

Comments

  • alvinleetya
    alvinleetya about 4 years

    I'm working on a segmentation algorithme for medical images and during the process it must display the evolving contour on the original image.
    I'm working with greyscale JPEG. In order to display the contours I use the drawContours function but I can't manage to draw a color contour. I would like to draw a red contour on the greyscale image but it only appears black or white.
    Here is the section of the code:

    Mat_<uchar> matrix = imread(path,0);
    int row = matrix.rows;
    int col = matrix.cols;
    Mat_<uchar> maskInter(row,col);
    for (int i=0; i<row; i++)
        for (int j=0; j<col; j++)
        {
            if ((double)matrix(i,j) <0)
            {maskInter(i,j)=255;}
            else
            {maskInter(i,j)=0;}
        };
    
    vector<vector<Point> > contours; 
    vector<Vec4i> hierarchy;
    Mat mat_out = maskInter.clone();
    findContours( mat_out, contours, hierarchy, CV_RETR_TREE , CHAIN_APPROX_SIMPLE);
    
    drawContours( img, contours, -1, RGB(255,0,0),1.5,8,hierarchy,2,Point());
    namedWindow(title);
    moveWindow(title, 100, 100);
    imshow(title, img);
    waitKey(0);
    

    Is it possible to display a color contour on a greyscale image?
    Thanks

  • cfo
    cfo over 11 years
    welcome! can the down-voter give a reason or improvement to my answer?
  • ArtemStorozhuk
    ArtemStorozhuk over 11 years
    Your final statement is wrong. And your answer isn't significantly different from my answer.
  • alvinleetya
    alvinleetya over 11 years
    @Astor I have found cfo's answer more helpful. There is just one thing that I don't undersand: When I'm trying to draw a line or a contour using cvDrawContour or cv::Line on the image img_rgb I can only use red, green or blue. If I use CV_RGB(255,0,0) it will be red, CV_RGB(0,255,0) it will be green... but if I want to use orange (CV_RGB(253,152,0) for example) it draws in white (or black depending on the values of R, G, B).