title: OpenCV 2: How to save a ROI
body: <p>I am new to OpenCV. Currently, trying to load and save a defined ROI of an image.
  For OpenCV 1.x, I got it working with the following function...</p>
  
  <pre><code>#include &lt;cv.h&gt;
  #include &lt;opencv2/core/core.hpp&gt;
  #include &lt;opencv2/highgui/highgui.hpp&gt;
  #include &lt;opencv2/imgproc/imgproc.hpp&gt;  
  
  void SaveROI(const CStringA&amp; inputFile, const CStringA&amp; outputFile)
  {
      if (ATLPath::FileExists(inputFile))
      {
          CvRect rect;
          rect.x      = 8;
          rect.y      = 90;
          rect.width  = 26;
          rect.height = 46;
  
          IplImage* imgInput = cvLoadImage(inputFile.GetString(), 1); 
          IplImage* imgRoi   = cvCloneImage(imgInput);
          cvSetImageROI(imgRoi, rect);
          cvSaveImage(outputFile.GetString(), imgRoi);
  
          cvReleaseImage(&amp;imgInput);
          cvReleaseImage(&amp;imgRoi);
      }
  }
  </code></pre>
  
  <p>How can this be done with the OpenCV 2 or C++. I tried the following without a success, the whole image is saved.</p>
  
  <pre><code>void SaveROICPP(const CStringA&amp; inputFile, const CStringA&amp; outputFile)
  {      
      if (ATLPath::FileExists(inputFile))
      {
          cv::Mat imgInput = cv::imread(inputFile.GetString());
  
          if (imgInput.data != NULL)
          {
              cv::Mat imgRoi = imgInput(cv::Rect(8, 90, 26, 46));
  
              imgInput.copyTo(imgRoi);                 
  
              cv::imwrite(outputFile.GetString(), imgRoi);
          }
      }
  }
  </code></pre>
  
  <p>Any help or suggestion?</p>