openCV - 在灰度图像上绘制颜色轮廓

时间:2012-11-18 16:11:16

标签: image opencv colors contour grayscale

我正在研究医学图像的分割算法,在此过程中,它必须在原始图像上显示不断变化的轮廓。
我正在使用灰度JPEG。为了显示轮廓,我使用drawContours函数,但我无法绘制颜色轮廓。我想在灰度图像上绘制一个红色轮廓,但它只显示为黑色或白色 以下是代码部分:

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);

是否可以在灰度图像上显示颜色轮廓? 感谢

2 个答案:

答案 0 :(得分:11)

您需要一个3通道(RGB)图像才能绘制和显示颜色。您的Mat_<uchar> matrix只是一个频道。您可以将灰度图像转换为彩色图像,如下所示:

  // 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);

答案 1 :(得分:0)

  

是否可以在灰度图像上显示颜色轮廓?

如果它真的是灰度(每像素1个字节)而不是,那么你不能。要绘制颜色轮廓,您应该使用cvtColor并在此绘制颜色轮廓之后将图像转换为RGB(每像素3个字节)。

相关问题