转自1:http://blog.csdn.net/lejun2011/article/details/7599912
转自2:http://blog.csdn.net/dujian996099665/article/details/8897077
为了提取到一幅图像中感兴趣的区域并裁剪出来作为一幅新图像的方法:
1、利用void cvSetImageROI( IplImage* image, CvRect rect )函数设置感兴趣的区域;
IplImage* src = cvLoadImage(“D:\\test.jpg”,1);
cvSetImageROI(src,cvRect(0,0,0.5*src->width,0.5*src->height));
2、创建一个与感兴趣区域同样大小的新图像;
IplImage* dst = cvCreateImage(cvSize(0.5*src->width,0.5*src->height),src->depth,src->nchannels);
3、利用void cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask=NULL )函数将设置了感兴趣区域的图像复制到新图像;
cvCopy(src,dst,0);
4、释放感兴趣区域。
cvResetImageROI(src);
代码如下:
// Cut_image.cpp : 定义控制台应用程序的入口点。 // /*********************************************************************** * OpenCV 2.4.4 测试例程 ***********************************************************************/ #include "stdafx.h" #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <vector> using namespace std; using namespace cv; //剪切图片为m * n 块 void Cut_img(Mat src_img,int m,int n,Vector<Mat> ceil_img){ int t = m * n; int height = src_img.rows; int width = src_img.cols; int ceil_height = height/m; int ceil_width = width/n; Mat roi_img,tmp_img; Point p1,p2; for(int i = 0;i<m;i++) for(int j = 0;j<n;j++){ //p1 = Rect rect(i+j*ceil_width,j+i*ceil_height,ceil_width,ceil_height); src_img(rect).copyTo(roi_img); ceil_img.push_back(roi_img); imshow("roi_img",roi_img); //getchar(); waitKey(0); //rectangle(i+j*ceil_width,j+i*ceil_height,); } } void show_images(Vector<Mat> imgs,int n){ //do something } int _tmain(int argc, _TCHAR* argv[]) { Mat img = imread("D://input//lena.jpg",1); imshow("src img",img); int m = 3; int n = 3; Vector<Mat> ceil_img = m*n; Cut_img(img,m,n,ceil_img); waitKey(); return 0; }