简体   繁体   English

检查cv :: Point是否在cv :: Mat中

[英]Check if a cv::Point is inside a cv::Mat

Does anyone know if Opencv provide a function to check if a cv::Point is inside a cv::Mat ? 有谁知道Opencv是否提供了一个函数来检查cv :: Point是否在cv :: Mat中?

Basically I am doing: 基本上我在做:

int x = (current.x - offset);
int y = current.y;
if (x >= 0 && y >= 0 && x < mat.cols &&  y < mat.rows) && ((int)mat.at<uchar>(y, x) == 0)){
        return cv::Point(x, y);
    }
}

I would like to know if there is something faster ? 我想知道是否有更快的东西? Or if this was bad to do this ? 或者如果这样做不好?

You can construct a cv::Rect of the size as the cv::Mat and use its contains() method: 你可以构造一个大小为cv::Matcv::Rect并使用它的contains()方法:

cv::Rect rect(cv::Point(), mat.size());
cv::Point p(x, y);

if (rect.contains(p) && mat.at<uchar>(y, x) == 0)
{
  return p;
}

Alternatively, you can catch exceptions in at() if indices are out of bounds: 或者,如果索引超出范围,您可以在at()捕获异常:

UPD: As properly mentioned by @Antonio in the comments, the following works only in debug mode, since " For the sake of higher performance, the index range checks are only performed in the Debug configuration ", which is kind of surprising and is different from how std::vector::at() works. UPD:正如@Antonio在评论中正确提到的,以下仅适用于调试模式,因为“ 为了更高的性能,索引范围检查仅在调试配置中执行 ”,这有点令人惊讶且不同从std::vector::at()工作原理。

try
{
  if (mat.at<uchar>(y, x) == 0)
  {
    return cv::Point(x, y);
  }
}
catch (cv::Exception& e)
{
}

However, be aware of the potential performance penalty caused by exceptions. 但是,请注意异常导致的潜在性能损失。 You shouldn't use the latter approach if this statement is executed in a loop or just very often. 如果此语句在循环中执行或者经常执行,则不应使用后一种方法。 Or in case it is normal rather than exceptional situation. 或者万一是正常而非特殊情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM