pointPolygonTest函数

1、pointPolygonTest函数

函数作用:

用于检测一个点是不是在轮廓上或者多边形上,,或者计算点到轮廓或者多边形的距离


2、pointPolygonTest函数调用形式

C++: double pointPolygonTest(InputArray contour, Point2f pt, bool measureDist)

参数详解:

InputArray contour:表示轮廓或者多边形

 Point2f pt:所检测的二维点,float型的点(x,y)坐标的点

bool measureDist:表示是不是检测到轮廓的距离,当是true检测点到轮廓的距离,是false检测点是不是在轮廓上


opencv代码:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include 
#include 
#include 

using namespace cv;
using namespace std;

/** @function main */
int main( int argc, char** argv )
{
  /// 创建一个图形     const int r = 100;
  Mat src = Mat::zeros( Size( 4*r, 4*r ), CV_8UC1 );

  /// 绘制一系列点创建一个轮廓:
  vector vert(6);

  vert[0] = Point( 1.5*r, 1.34*r );
  vert[1] = Point( 1*r, 2*r );
  vert[2] = Point( 1.5*r, 2.866*r );
  vert[3] = Point( 2.5*r, 2.866*r );
  vert[4] = Point( 3*r, 2*r );
  vert[5] = Point( 2.5*r, 1.34*r );

  /// 在src内部绘制
  for( int j = 0; j < 6; j++ )
     { line( src, vert[j],  vert[(j+1)%6], Scalar( 255 ), 3, 8 ); }

  /// 得到轮廓
  vector > contours; vector hierarchy;
  Mat src_copy = src.clone();

  findContours( src_copy, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);

  /// 计算到轮廓的距离
  Mat raw_dist( src.size(), CV_32FC1 );

  for( int j = 0; j < src.rows; j++ )
     { for( int i = 0; i < src.cols; i++ )
          { raw_dist.at(j,i) = pointPolygonTest( contours[0], Point2f(i,j), true ); }
     }

  double minVal; double maxVal;
  minMaxLoc( raw_dist, &minVal, &maxVal, 0, 0, Mat() );
  minVal = abs(minVal); maxVal = abs(maxVal);

  /// 图形化的显示距离
  Mat drawing = Mat::zeros( src.size(), CV_8UC3 );

  for( int j = 0; j < src.rows; j++ )
     { for( int i = 0; i < src.cols; i++ )
          {
            if( raw_dist.at(j,i) < 0 )
              { drawing.at(j,i)[0] = 255 - (int) abs(raw_dist.at(j,i))*255/minVal; }
            else if( raw_dist.at(j,i) > 0 )
              { drawing.at(j,i)[2] = 255 - (int) raw_dist.at(j,i)*255/maxVal; }
            else
              { drawing.at(j,i)[0] = 255; drawing.at(j,i)[1] = 255; drawing.at(j,i)[2] = 255; }
          }
     }

  /// 创建窗口显示结果
  char* source_window = "Source";
  namedWindow( source_window, CV_WINDOW_AUTOSIZE );
  imshow( source_window, src );
  namedWindow( "Distance", CV_WINDOW_AUTOSIZE );
  imshow( "Distance", drawing );

  waitKey(0);
  return(0);
}


你可能感兴趣的:(pointPolygonTest函数)