http://blog.csdn.net/wuxiaoyao12/article/details/7305865
版权声明:本文为博主原创文章,未经博主允许不得转载。
Rect rect(10, 20, 100, 50);
Mat image_roi = image(rect);
分割/聚合颜色平面
split( );
merge( );
案例一、得到由矩形提取到的图像
第一步,把截取图像中需要的区域存入矩阵。
CvMat* cvGetSubRect(const CvArr* arr, CvMat* submat, CvRect rect);
把IplImage *传给arr,IplImage *指向所要截取的图像;
把CvMat *传给submat;
rect是要截取的区域;
返回指向所存矩阵。
例如:
CvMat *pMat = cvCreateMatHeader(100, 100, CV_8UC1); //创建一个100*100的矩阵头
CvRect rect = cvRect(0, 0, 100, 100); //要截取的区域,与创建的矩阵大小一样
cvGetSubRect(pImg, pMat, rect); //pImg为指向图像的指针,pMat指向存储所接图像的矩阵,返回值和pMat相等
也可以简化为:
CvMat *pMat = cvGetSubRect(pImg, cvCreateMatHeader(100, 100, CV_8UC1), cvRect(0, 0, 100, 100));
第二步,把刚才存入矩阵的数据转存为图像。
IplImage* cvGetImage( const CvArr* arr, IplImage* image_header );
把CvMat *传给arr;image_header;
只需为图像头就行,不用分配数据存储空间 ;
返回所存图像的指针。
例如:
IplImage *pSubImg = cvCreateImageHeader(cvSize(100, 100), 8, 1); //创建一个100*100的图像头
cvGetImage(pMat, pSubImg); //pMat为存储数据的矩阵,pSubImg指向图像,返回值与pSubImg相等
也可以简化为:
IplImage *pSubImg = cvGetImage(pMat, cvCreateImageHeader(cvSize(100, 100), 8, 1));
案例二、得到任意形状区域
第一步、在图片上画出来
- #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");
- }