// 矩形截图 bool Screenshot( IplImage* src, IplImage* dst, CvRect rect ) { cvSetImageROI( src, rect ); cvCopy( src, dst, 0 ); cvResetImageROI( src ); return 0; } // 安全重置矩形大小 void SafeResetSizeOfRect( IplImage* src, CvRect& rect ) { rect.x = rect.x < 0 ? 0 : rect.x; rect.y = rect.y < 0 ? 0 : rect.y; rect.width = rect.width < 0 ? 0 : rect.width; rect.height = rect.height < 0 ? 0 : rect.height; if ( rect.x > src->width || rect.y > src->height ) { rect = cvRect( 0, 0, src->width, src->height ); } rect.width = std::min( rect.width, src->width - rect.x ); rect.height = std::min( rect.height, src->height - rect.y ); }
int _tmain(int argc, _TCHAR* argv[]) { const char *srcPath = "F:\\图片\\00test.jpg"; const char *saveFilePath = "F:\\图片\\00res.jpg"; CvRect rect = cvRect( 10, 10, 100, 100 ); IplImage *img = cvLoadImage( srcPath, 1 ); IplImage *dst = 0; SafeResetSizeOfRect( img, rect ); dst = cvCreateImage( cvSize(rect.width, rect.height), img->depth, img->nChannels ); Screenshot( img, dst, rect ); cvSaveImage( saveFilePath, dst ); cvReleaseImage( &img ); cvReleaseImage( &dst ); return 0; }
SafeResetSizeOfRect这个函数的作用调整rect矩形的大小,防止它超过img图像的尺寸范围
时间: 2024-10-24 16:46:12