title: OpenCV extract area of an image from a vector of squares
body: <p>I have an image that contains a square, and I need to extract the area contained in that square.
  After applying the <strong>squares.c</strong> script (available in the samples of every OpenCV distribution) I obtain a vector of squares, then I need to save an image for each of them.</p>
  
  <p>The user <strong>karlphillip</strong> suggested this:</p>
  
  <pre><code>for (size_t x = 0; x &lt; squares.size(); x++) 
  {
      Rect roi(squares[x][0].x, squares[x][0].y, 
               squares[x][1].x - squares[x][0].x, 
               squares[x][3].y - squares[x][0].y);
      Mat subimage(image, roi);
  }
  </code></pre>
  
  <p>in order to generate a new Mat called subimage for all the squares detected in the original image</p>
  
  <p>As karl remembered me, the points detected in the image may not represent a perfect square (as you can see in the image above) but the code I just suggested to you assumes they do.</p>
  
  <p>In fact I get this error:</p>
  
  <pre><code>OpenCV Error: Assertion failed (0 &lt;= roi.x &amp;&amp; 0 &lt;= roi.width &amp;&amp;
        roi.x + roi.width &lt;= m.cols &amp;&amp; 0 &lt;= roi.y &amp;&amp; 0 &lt;= roi.height &amp;&amp;
        roi.y + roi.height &lt;= m.rows) in Mat, file /usr/include/opencv/cxmat.hpp, 
        line 187
  
  terminate called after throwing an instance of 'cv::Exception'
  what():  /usr/include/opencv/cxmat.hpp:187: error: (-215) 0 &lt;= roi.x &amp;&amp; 
         0 &lt;= roi.width &amp;&amp; roi.x + roi.width &lt;= m.cols &amp;&amp; 0 &lt;= roi.y &amp;&amp;
         0 &lt;= roi.height &amp;&amp; roi.y + roi.height &lt;= m.rows in function Mat
  
  Aborted
  </code></pre>
  
  <p>Suggestion for make the script accept also non perfect squares?</p>