最新的:
cv::Mat img;
a=
cv::Mat m0 = img(cv::Rect(i0, i1, w, h))
以前的:
//opencv
#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
/******************************************************************************************
Function: Screenshot
Description: 矩形截图
Input: src:原图片 rect:截图范围
Output: dst:截图后的图片
Return: 截图成功返回true,失败返回false
*******************************************************************************************/
bool Screenshot(IplImage* src, IplImage* dst, CvRect rect)
{
try {
cvSetImageROI(src, rect);
cvCopy(src, dst, 0);
cvResetImageROI(src);
return true;
}
catch (cv::Exception e)
{
}
}
/******************************************************************************************
Function: SafeResetSizeOfRect
Description: 安全重置矩形大小
Input: src:原图片 rect:截图范围
Return: 无
*******************************************************************************************/
void SafeResetSizeOfRect(IplImage* src, CvRect& rect)
{
try
{
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);
}
catch (cv::Exception e)
{
}
}
//调用举例
IplImage *src = 0;
IplImage *dst = 0;
src = cvLoadImage("D:\\1.jpg", CV_LOAD_IMAGE_COLOR);
//定义截图范围
CvRect rect = cvRect(720, 610, 300, 320);
//截图
SafeResetSizeOfRect(src, rect);
dst = cvCreateImage(cvSize(rect.width, rect.height), src->depth, src->nChannels);
Screenshot(src, dst, rect);
//保存图片
cvSaveImage("D:\\rect.jpg", dst);
//释放内存
cvReleaseImage(&src);
cvReleaseImage(&dst);