title: Submatrix out of bounds (OpenCV)
body: <p>I'm trying to divide an image into a grid, and save the individual pieces. At the moment I loop through the piece number and get a sub-image, which I then save. </p>
  
  <p>Can someone explain how to get the sub-images properly? I've been following similar posts on stackoverflow, but my code keeps failing an assertion which checks the bounds of the sub-image vs. the original.</p>
  
  <pre><code>int unitWidth = image.rows / n;
  int unitHeight = image.cols / n;
  for(int i=0; i&lt;n; i++) {
      //Take the next tile in the nxn grid. Unit is the width and height of
      //each tile. i%n and i/n are just fancy ways of a double x,y for loop
      Mat subImage = image(Rect((i % n) * unitWidth, (i / n) * unitHeight, unitWidth,unitHeight));
  
      ostringstream oss;
      oss &lt;&lt; i &lt;&lt; "_" &lt;&lt; n &lt;&lt; ".jpg";
      string name = oss.str();
      imwrite(name, subImage);
  }
  </code></pre>
  
  <p>p.s. the first subimage doesn't break the program, but the second does (for a 2x2 grid, so an end piece). I've shortening the sub-image by 10, but that still broke the machine.</p>