C++ 從一幅圖片上裁取需要的區域
阿新 • • 發佈:2019-01-07
1、Mat
Mat src, image_src; //原圖 Mat imageROI; //ROI區域 Mat TempImg; //裁取出的區域儲存為Mat int x_begin, y_begin, width, height; //裁取區域的座標及大小 int srcWidth, srcHeight; //儲存原圖寬、高 //賦初值 x_begin = 0; y_begin = 0; width = 100; height = 100; //讀取原圖 src = imread("test.jpg", 1); if(!src.data){ cout<<" image read error!"<<endl; return -1; } srcWidth = src.cols; //獲取原圖寬、高 srcHeight = src.rows; //控制裁取區域不超過原圖 if(width < 1 || height < 1 || width > srcWidth || height > srcHeight){ LOOGE<<"[Rect error: srcWidth = "<<srcWidth<<", srcHeight = "<<srcHeight<<", x_begin = " <<x_begin<<", y_begin = "<<y_begin<<", width = "<<width<<", height = "<<height<<" ]"; return -1; } if(x_begin + width > srcWidth) width = srcWidth - x_begin; if(y_begin + height > srcHeight) height = srcHeight - y_begin; //區域裁取 image_src = src.clone(); //備份原圖 imageROI = image_src(Rect(x_begin, y_begin, width, height)); //設定待裁取ROI imageROI.convertTo(TempImg, TempImg.type()); //將ROI區域拷貝至dst
2、IplImage
int x_begin, y_begin, width, height; //裁取區域的座標及大小 int srcWidth, srcHeight; //原圖寬、高 //賦初值 x_begin = 0; y_begin = 0; width = 100; height = 100; //讀取原圖 IplImage* src = cvLoadImage("test.jpg", 1); if(!src){ cout<<" image read error!"<<endl; cvReleaseImage(&src); return -1; } srcWidth = image->width; //獲取原圖寬、高 srcHeight = image->height; //控制裁取區域不超過原圖 if(width < 1 || height < 1 || width > srcWidth || height > srcHeight){ LOOGE<<"[Rect error: srcWidth = "<<srcWidth<<", srcHeight = "<<srcHeight<<", x_begin = " <<x_begin<<", y_begin = "<<y_begin<<", width = "<<width<<", height = "<<height<<" ]"; cvReleaseImage(&src); return -1; } if(x_begin + width > srcWidth) width = srcWidth - x_begin; if(y_begin + height > srcHeight) height = srcHeight - y_begin; //區域裁取 IplImage* image_src = cvCloneImage(src); //備份原圖 cvSetImageROI(image_src, cvRect(x_begin, y_begin, width, height)); //設定待裁取ROI IplImage* dst = cvCreateImage(cvSize(width, height), src->depth, src->nChannels); //建立裁取區域大小的IplImage* cvCopy(image_src, dst); //將ROI區域拷貝至dst //釋放資源 cvReleaseImage(&src); cvResetImageROI(image_src); cvReleaseImage(&image_src);