如何在opencv中使用findcontours方法查找图像的坐标点

时间:2015-09-07 04:00:40

标签: c++ qt opencv

在这里,我进行了编码以找到图像的边缘及其所有坐标点,但我只需要图像中每个象限的两个或三个坐标点。

using namespace cv;
using namespace std;
Mat src; 
Mat src_gray;
int thresh = 172;
int max_thresh = 255;
RNG rng(12345);

void thresh_callback(int, void* );

int main( int argc, char** argv ){
src = imread("Led50.jpg",1);
cvtColor( src, src_gray, CV_BGR2GRAY );
blur( src_gray, src_gray, Size(3,3) );
char* source_window = "Source";
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
imshow( source_window, src );
createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback );
thresh_callback( 0, 0 );
waitKey(0);
return(0);}

void thresh_callback(int, void* ){
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Canny( src_gray, canny_output, thresh, thresh*2, 3 );
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
for(unsigned int i=0;i<contours.size();i++){

   for(unsigned int j=0;j<contours[i].size();j++)
   {
       cout << "Point(x,y)=" << contours[i][j].x << "," << contours[i][j].y << endl;

   }}}

源文件:Source file

结果,我得到所有坐标点:Result and i get all the coordinate point

我只需要标记坐标点但不需要准确位置,每个象限至少有两个点:And I need only marked coordinate point but not in exact position as well as each quadrant atleast have two points

上面的代码基于canny和findcontours,我需要很少的图像坐标。

1 个答案:

答案 0 :(得分:4)

#include "highgui.hpp"
#include "imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv ){

Mat src_gray;
src_gray = imread("EXnc1.jpg",0);
blur( src_gray, src_gray, Size(3,3) );

Mat bwimg = src_gray > 127;
vector<vector<Point> > contours;

findContours( bwimg, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE );

for(unsigned int i=0;i<contours.size();i++){
approxPolyDP(Mat(contours[i]), contours[i], 10, true);

   if(i > 0)
   {
    cout << "Outer contour points \n";
   }
   else cout << "Inner contour points \n";

   for(unsigned int j=0;j<contours[i].size();j++)
   {
    cout << "Point(x,y)=" << contours[i][j].x << "," << contours[i][j].y << endl;
   circle( src_gray, contours[i][j], 3, Scalar(0, 0, 255), FILLED, LINE_AA );
   }
imshow( "Result", src_gray );
waitKey(0);
   }

return(0);}

输出: enter image description here

Inner contour points
Point(x,y)=343,148
Point(x,y)=419,160
Point(x,y)=461,208
Point(x,y)=457,276
Point(x,y)=403,322
Point(x,y)=322,322
Point(x,y)=269,262
Point(x,y)=279,190
Outer contour points
Point(x,y)=371,133
Point(x,y)=289,159
Point(x,y)=251,224
Point(x,y)=271,298
Point(x,y)=351,341
Point(x,y)=436,320
Point(x,y)=481,247
Point(x,y)=456,172