如何访问Opencv中的RGB值?

我对使用多个频道感到困惑。 哪一个是正确的以下?

// roi is the image matrix

for(int i = 0; i < roi.rows; i++)
{
    for(int j = 0; j < roi.cols; j+=roi.channels())
    {
        int b = roi.at<cv::Vec3b>(i,j)[0];
        int g = roi.at<cv::Vec3b>(i,j)[1];
        int r = roi.at<cv::Vec3b>(i,j)[2];
        cout << r << " " << g << " " << b << endl ;
    }
}

要么,

for(int i = 0; i < roi.rows; i++)
{
    for(int j = 0; j < roi.cols; j++)
    {
        int b = roi.at<cv::Vec3b>(i,j)[0];
        int g = roi.at<cv::Vec3b>(i,j)[1];
        int r = roi.at<cv::Vec3b>(i,j)[2];
        cout << r << " " << g << " " << b << endl ;
    }
}

第二个是正确的,Mat内部的行和列表示像素的数量,而通道与行和列数无关。 并且CV默认使用BGR,因此假设Mat未转换为RGB,那么代码是正确的

参考,个人经验,OpenCV文档


从图像中获取颜色分量的更快捷方式是将图像表示为IplImage结构,然后利用像素大小和通道数量使用指针算法遍历它。

例如,如果您知道您的图像是一个3像素图像,每像素1个字节,格式为BGR(OpenCV中的默认设置),则以下代码将访问其组件:

(在下面的代码中, imgIplImage类型。)

for (int y = 0; y < img->height; y++) {
    for(int x = 0; x < img->width; x++) {
        uchar *blue = ((uchar*)(img->imageData + img->widthStep*y))[x*3];
        uchar *green = ((uchar*)(img->imageData + img->widthStep*y))[x*3+1];
        uchar *red = ((uchar*)(img->imageData + img->widthStep*y))[x*3+2];
    }
}

对于更灵活的方法,你可以使用CV_IMAGE_ELEM中定义的宏types_c.h

/* get reference to pixel at (col,row),
   for multi-channel images (col) should be multiplied by number of channels */
#define CV_IMAGE_ELEM( image, elemtype, row, col )       
    (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)])

我想第二个是正确的,但获得这样的数据是非常耗时的。

一个更快的方法是使用IplImage *数据结构,并将指向的地址与roi中包含的数据大小相加。

链接地址: http://www.djcxy.com/p/11485.html

上一篇: How to access the RGB values in Opencv?

下一篇: TypeScript source map files don't work with Chrome