opencv图像分割

原图

 

  1: //转换为灰度图
  2: IplImage* pGrayImage = cvLoadImage( "image0.bmp", 0);

 

  1: //利用Canny算子进行边缘检测
  2: IplImage * pCannyImg=cvCreateImage(cvGetSize(pGrayImage),pGrayImage->depth,1);
  3: cvCanny(pGrayImage,pCannyImg,50,150,3);

 

  1: //膨胀,使边缘轮廓闭合
  2: IplImage * pDilateImg=cvCreateImage(cvGetSize(pGrayImage),pGrayImage->depth,1);
  3: IplConvKernel *rect_2;
  4: rect_2 = cvCreateStructuringElementEx(2, 3, 1, 1, CV_SHAPE_RECT);
  5: cvDilate(pCannyImg, pDilateImg);

 

  1: //检测图片轮廓
  2: CvMemStorage * storage = cvCreateMemStorage(0);
  3: CvSeq * contour = 0;
  4: int mode = CV_RETR_EXTERNAL;
  5: int num = cvFindContours(pDilateImg,storage,&contour,sizeof(CvContour),
  6:         CV_RETR_LIST,CV_CHAIN_APPROX_NONE, cvPoint(0,0) );
  7:
  8: //用白色填充面积最大的轮廓
  9: double maxArea = 2000;
 10: IplImage* pContourImg = cvCreateImage(cvGetSize(pCannyImg), IPL_DEPTH_8U, 3);
 11: //初始化为黑色
 12: cvZero(pContourImg);
 13: while(contour)
 14: {
 15:     double area=fabs(cvContourArea(contour, CV_WHOLE_SEQ));
 16:      if(area > maxArea)
 17:      {
 18:          cvDrawContours(pContourImg,contour,cvScalarAll(255),cvScalarAll(0),0,CV_FILLED);
 19:      }
 20:      contour=contour->h_next;
 21: }
 22: cvReleaseMemStorage(&storage);

 

  1: //填充图作为mask,与原图像进行按像素与操作
  2: IplImage* pColorImage = cvLoadImage( "image0.bmp", -1);
  3: for(int height=0; height<240 ; height++)
  4: {
  5:     for(int width = 0; width < 320; width++)
  6:     {
  7:         int piex = height*320+width;
  8:         if((BYTE)pContourImg->imageData[piex*3] != 255u)
  9:         {
 10:              pColorImage->imageData[piex*3] = 0;
 11:              pColorImage->imageData[piex*3+1] = 0;
 12:              pColorImage->imageData[piex*3+2] = 0;
 13:         }
 14:      }
 15:  }
 16:
 17: //显示保存图像
 18: cvShowImage( "output", pColorImage);
 19: cvSaveImage("output.bmp", pColorImage);
 20:
 21: //释放资源
 22: cvReleaseImage(&pColorImage);
 23: cvReleaseImage(&pGrayImage);
 24: cvReleaseImage(&pCannyImg);
 25: cvReleaseImage(&pDilateImg);
 26: cvReleaseImage(&pContourImg);

你可能感兴趣的:(opencv图像分割)