OpenCV: 寻找图像轮廓并绘制

#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include<windows.h>




//Some defines we left out of the book
#define CVX_RED CV_RGB(0xff,0x00,0x00)
#define CVX_GREEN CV_RGB(0x00,0xff,0x00)
#define CVX_BLUE CV_RGB(0x00,0x00,0xff)


//  Example 8-3. Finding and drawing contours on an input image
int main(int argc, char* argv[]) {


  cvNamedWindow( "lkjc", 1 );
  IplImage* img_8uc1 = NULL;
  
  //Changed this a little for safer image loading and help if not
  if( argc != 1 || !(img_8uc1 = cvLoadImage( "T_signs.jpg", CV_LOAD_IMAGE_GRAYSCALE )) ){
  printf("\nExample 8_3 Drawing Contours\nCall is:\n./ch8_ex8_3 image\n\n");///* 8 bit unless combined with CV_LOAD_IMAGE_ANYDEPTH, color */


  return -1;}
  
  
  IplImage* img_edge = cvCreateImage( cvGetSize(img_8uc1), 8, 1 );
  IplImage* img_8uc3 = cvCreateImage( cvGetSize(img_8uc1), 8, 3 );
  cvThreshold( img_8uc1, img_edge, 128, 255, CV_THRESH_BINARY );//对数组元素进行固定阈值操作 




  CvMemStorage* storage = cvCreateMemStorage();
  CvSeq* first_contour = NULL;
  int Nc = cvFindContours(//在二值图像中寻找轮廓
     img_edge,
     storage,
     &first_contour,
     sizeof(CvContour),
     CV_RETR_LIST // Try all four values and see what happens
  );
  int n=0,k;
  printf("\n\nHit any key to draw the next contour, ESC to quit\n\n");
  printf( "Total Contours Detected: %d\n", Nc );
  for( CvSeq* c=first_contour; c!=NULL; c=c->h_next ) {
     cvCvtColor( img_8uc1, img_8uc3, CV_GRAY2BGR );
     cvDrawContours(//在图像中绘制外部和内部的轮廓
        img_8uc3,
        c,
        CVX_RED,  //Yarg, these are defined above, but not in the book.  Oops
        CVX_BLUE,
        0,        // 如果等级为0,绘制单独的轮廓Try different values of max_level, and see what happens
        2,
        8
     );
     printf("Contour #%d\n", n );
     cvShowImage( "lkjc", img_8uc3 );
     printf(" %d elements:\n", c->total );
     for( int i=0; i<c->total; ++i ) {
     CvPoint* p = CV_GET_SEQ_ELEM( CvPoint, c, i );
        printf("    (%d,%d)\n", p->x, p->y );
     }
     if((k = cvWaitKey()&0x7F) == 27)
       break;
     n++;
  }
  printf("Finished all contours. Hit key to finish\n");
  cvCvtColor( img_8uc1, img_8uc3, CV_GRAY2BGR );
  cvShowImage( "lkjc", img_8uc3 );
  cvWaitKey(0);
  cvDestroyWindow( "lkjc" );
  cvReleaseImage( &img_8uc1 );
  cvReleaseImage( &img_8uc3 );
  cvReleaseImage( &img_edge );
     system("pause");


  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值