【问题标题】:Find pixel color out of cv::Mat on specific position在特定位置从 cv::Mat 中查找像素颜色
【发布时间】:2012-08-23 17:10:27
【问题描述】:

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

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 是比较正确的值吗?

非常感谢

【问题讨论】:

标签: opencv colors matrix pixel


【解决方案1】:

这取决于您图片的频道。 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 查找您需要的矩形。

【讨论】:

  • 频道 == 1 似乎有效,不幸的是 if (outputFrame.at&lt;uchar&gt;(y,x) == 255) 总是正确的,你有解决这个问题的想法吗?
  • 你有白色图像。发表它。还有为什么(y,x) 不是(x,y)
  • 工作,我很愚蠢,第一帧总是白色的,但由于每个像素的 cout 非常慢,我从不等到第一帧被处理。非常感谢!我也会尝试轮廓检测。再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多