c++ opencv roi

 


最新的:
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);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章