Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a cv::Point is inside a cv::Mat

Tags:

c++

opencv

Does anyone know if Opencv provide a function to check if a cv::Point is inside a 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 ?

like image 375
Poko Avatar asked Jun 21 '13 13:06

Poko


1 Answers

You can construct a cv::Rect of the size as the cv::Mat and use its contains() method:

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:

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.

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.

like image 169
Mikhail Avatar answered Nov 11 '22 16:11

Mikhail