opencv 任意图形截取

转自:http://blog.csdn.net/wuxiaoyao12/article/details/7305865

得到任意形状区域

第一步、在图片上画出来

#include "cv.h"  
#include "highgui.h"  
#include <stdio.h>  
#include <stdlib.h>  
  
IplImage* inpaint_mask = 0;  
IplImage* img0 = 0, *img = 0, *inpainted = 0;  
CvPoint prev_pt = {-1,-1};  
  
void on_mouse( int event, int x, int y, int flags, void* zhang)  
{  
  if( !img )  
   return;  
  if( event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON) )  
    prev_pt = cvPoint(-1,-1);//初始化  
  else if( event == CV_EVENT_LBUTTONDOWN )  
    prev_pt = cvPoint(x,y);  
  else if( event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON) )  
  {//手一直在绘画  
    CvPoint pt = cvPoint(x,y);  
    if( prev_pt.x < 0 )  
    prev_pt = pt;  
    cvLine( inpaint_mask, prev_pt, pt, cvScalarAll(255), 5, 8, 0 );  
    cvLine( img, prev_pt, pt, cvScalarAll(255), 5, 8, 0 );  
    prev_pt = pt;  
    cvShowImage( "image", img );  
  }  
}  
  
int main( int argc, char** argv )  
{  
   char* filename = argc >= 2 ? argv[1] : (char*)"fruits.jpg";  
   if( (img0 = cvLoadImage(filename,-1)) == 0 )  
     return 0;  
   printf( "Hot keys: \n"  
   cvNamedWindow( "image", 1 );  
   img = cvCloneImage( img0 );  
   inpainted = cvCloneImage( img0 );  
   inpaint_mask = cvCreateImage( cvGetSize(img), 8, 1 );  
   cvZero( inpaint_mask );  
   cvZero( inpainted );  
   cvShowImage( "image", img );  
   cvShowImage( "watershed transform", inpainted );  
   cvSetMouseCallback( "image", on_mouse, 0 );     
}  


第二步、将选择的区域提取出来

if(event == CV_EVENT_RBUTTONUP)  
{  
   cvFloodFill(maskImg,cvPoint(x,y),cvScalarAll(255));  
   cvSaveImage("maskImg.bmp",maskImg);  
   IplImage *segImage=cvCreateImage(cvGetSize(img),8,3);;  
   cvCopy(img,segImage,maskImg);  
   cvSaveImage("segImage.bmp",segImage);  
   cvCopy(segImage,proc->img);  
   cvReleaseImage(&segImage);  
   cvDestroyWindow("Key Image");  
}  


听说上面代码有点问题,评轮如下:

我觉得大神可能只是给了方法,最后的再进行显示和保存的时候,这部分代码以应该修改一下:
if(event == CV_EVENT_RBUTTONUP) ,如果直接把这个语句加上去,是无法被执行的,因为右键的相应被前面的判断
if( event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON) ) 都终止了,所以要执行第二部分,最简单的是把if(event == CV_EVENT_RBUTTONUP)改成if(event == CV_EVENT_LBUTTONDBLCLK),不然第一部分的判断应该修改下,第二部分的maskImg应该换成定义的前面定义的某个mask,这样就可以执行了

你可能感兴趣的:(opencv,任意图形截取)