title: Fastest way to crop an image without exceeding image dimensions in Matlab
body: <p>Using matlab.</p>
  
  <p>Suppose I have:</p>
  
  <ul>
  <li>An image <code>i</code> with "MaxWidth" number of pixels in the horizontal direction and "MaxHeight" number of pixels in the vertical direction. </li>
  <li>A retangular ROI defined by the coordinates of the top-left and bottom-right pixels as in </li>
  </ul>
  
  <p><code>ROI = [yleft , xleft ; yright , xright]</code></p>
  
  <p>I was wondering what would be the fastest way to compute <code>i_crop</code>, where <code>i_crop</code>is the image that contains only the pixels that were in <code>i</code> and inside the given ROI. </p>
  
  <p>ROI's like <code>[-10 , -10 ; 1000 , 1000]</code> in an 400x400 image should be regarded as <code>[1 , 1 ; 400 , 400]</code></p>
  
  <hr>
  
  <p>I came up with both of this so far:</p>
  
  <h2>crop1</h2>
  
  <pre><code>ROI(ROI&lt;1)=1;
  ROI(ROI(:,1)&gt;MaxHeight) = MaxHeight;
  ROI(find(ROI(:,2)&gt;MaxWidth)+2) = MaxWidth;
  i_crop = i(ROI(1,1):ROI(2,1),ROI(1,2):ROI(2,2),:); 
  </code></pre>
  
  <p>And</p>
  
  <h2>crop2</h2>
  
  <pre><code>ymin = ROI(1,1);
  xmin = ROI(1,2);
  ymax = ROI(2,1);
  xmax = ROI(2,2);
  
  if ymin &lt; 1
    ymin = 1;
  end
  if xmin &lt; 1
    xmin = 1;
  end
  if ymax &lt; 1
    ymax = 1;
  end
  if xmax &lt; 1
    xmax = 1;
  end
  
  if ymin &gt; MaxHeight
    ymin = MaxHeight;
  end
  if ymax &gt; MaxHeight
    ymax = MaxHeight;
  end
  if xmin &gt; MaxWidth
    xmin = MaxWidth;
  end
  if xmax &gt; MaxWidth
    xmax = MaxWidth;
  end
  
  i_crop = i(ymin:ymax,xmin:xmax,:);
  </code></pre>
  
  <p>The latter runs faster:</p>
  
  <pre><code>&gt;&gt; im = imread('peppers.png');
  &gt;&gt; tic, for i =1:100000 i_c = crop1(im,[0 0 ; 60 60],512,384); end; toc;
  Elapsed time is 2.053574 seconds.
  &gt;&gt; tic, for i =1:100000 i_c = crop2(im,[0 0 ; 60 60],512,384); end; toc;
  Elapsed time is 1.667059 seconds.
  </code></pre>
  
  <p>Hope I made myself clear, thank's in advance!</p>