在特定位置找到cv :: Mat的像素颜色

时间:2012-08-29 06:29:21

标签: opencv colors matrix pixel

我的问题是,我需要找到包含所有白色像素的cv :: Mat图像的子矩阵。因此,我想遍历所有像素,检查它们是否为白色并使用该信息构建cv :: Rect 我想出了如何遍历所有像素,但我不知道如何从中获取像素颜色。之前使用CV_GRAY2BGR

将cv :: Mat转换为灰度
for(int y = 0; y < outputFrame.rows; y++)
{
    for(int x = 0; x < outputFrame.cols; x++)
    {
        // I don't know which datatype I should use
        if (outputFrame.at<INSERT_DATATYPE_HERE>(x,y) == 255)
           //define area
    }
}

我的最后一个问题是,我应该在位置INSERT_DATATYPE_HERE的代码中插入哪种数据类型,并且255是与之比较的正确值?

非常感谢

1 个答案:

答案 0 :(得分:7)

这取决于您图片的频道。 Mat有方法channels。它返回通道数 - 如果图像为灰色,则一个;如果图像为彩色,则(例如,RGB - 每个颜色组件一个通道)。

所以你必须做这样的事情:

if (outputFrame.channels() == 1) //image is grayscale - so you can use uchar (1 byte) for each pixel
{
    //...
    if (outputFrame.at<uchar>(x,y) == 255)
    {
        //do a check if this pixel is the most left, or the most right, or the most top, or the most bottom (this is needed to construct result rectangle)
    }
}
else
if (outputFrame.channels() == 3) //image is color, so type of each pixel if Vec3b
{
    //...
    // white color is when all values (R, G and B) are 255
    if (outputFrame.at<Vec3b>(x,y)[0] == 255 && outputFrame.at<Vec3b>(x,y)[1] == 255 && outputFrame.at<Vec3b>(x,y)[2] == 255)
    {
        //do a check if this pixel is the most left, or the most right, or the most top, or the most bottom (this is needed to construct result rectangle)
    }
}

但实际上要获得包含图像上所有白色像素的矩形,您可以使用另一种技术:

  1. Convert image to grayscale
  2. 使用值254(或接近255)作为参数执行threshold
  3. Find all contours on image
  4. 构造一个包含所有这些轮廓的轮廓(简单地将每个轮廓的所有点添加到一个大轮廓中)。
  5. 使用bounding rectangle function查找矩形所需。
相关问题