Image Processing24(Convex Hull )

Goal

In this tutorial you will learn how to:

Theory

Code

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
Mat src; Mat src_gray;
int thresh = 100;
int max_thresh = 255;
RNG rng(12345);
void thresh_callback(int, void* );
int main( int argc, char** argv )
{
  CommandLineParser parser( argc, argv, "{@input | stuff.jpg | input image}" );
  src = imread( parser.get<String>( "@input" ), IMREAD_COLOR );
  if( src.empty() )
  {
    cout << "Could not open or find the image!\n" << endl;
    cout << "Usage: " << argv[0] << " <Input image>" << endl;
    return -1;
  }
  cvtColor( src, src_gray, COLOR_BGR2GRAY );
  blur( src_gray, src_gray, Size(3,3) );
  const char* source_window = "Source";
  namedWindow( source_window, WINDOW_AUTOSIZE );
  imshow( source_window, src );
  createTrackbar( " Threshold:", "Source", &thresh, max_thresh, thresh_callback );//滑动条
  thresh_callback( 0, 0 );
  waitKey(0);
  return(0);
}
void thresh_callback(int, void* )
{
  Mat threshold_output;
  vector<vector<Point> > contours;//轮廓点
  vector<Vec4i> hierarchy;//层次结构
  threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );//输入,输出,阀值
  findContours( threshold_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
  //输入,输出,轮廓点,层次结构,轮廓方法,逼近方法,偏移点
  vector<vector<Point> >hull( contours.size() );//凸包也是一个点集
  for( size_t i = 0; i < contours.size(); i++ )
     {   
      convexHull( contours[i], hull[i], false );  //输入,输出,顺时针
     }
  Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
  for( size_t i = 0; i< contours.size(); i++ )
     {
       Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
       drawContours( drawing, contours, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
       drawContours( drawing, hull, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
     }
  namedWindow( "Hull demo", WINDOW_AUTOSIZE );
  imshow( "Hull demo", drawing );

}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

set(CMAKE_CXX_FLAGS "-std=c++11")
project( DisplayImage )
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( DisplayImage main.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )


install(TARGETS DisplayImage RUNTIME DESTINATION bin

Results



猜你喜欢

转载自blog.csdn.net/qq_27806947/article/details/80318003