crop center portion of a numpy image
<p>Let's say I have a numpy image of some width x and height y.
I have to crop the center portion of the image to width cropx and height cropy. Let's assume that cropx and cropy are positive non zero integers and less than the respective image size. What's the best way to apply the slicing for the output image?</p>

<p>Thanks,
Gert</p>

<p>Thanks, Divakar.</p>

<p>Your answer got me going the right direction. I came up with this using negative slice offsets to count 'from the end':</p>

<pre><code>def cropimread(crop, xcrop, ycrop, fn):
    "Function to crop center of an image file"
    img_pre= msc.imread(fn)
    if crop:
        ysize, xsize, chan = img_pre.shape
        xoff = (xsize - xcrop) // 2
        yoff = (ysize - ycrop) // 2
        img= img_pre[yoff:-yoff,xoff:-xoff]
    else:
        img= img_pre
    return img
</code></pre>

<p>A few things I am not sure about.</p>

<ol>
<li>Will this work with odd image sizes and/or crop values?</li>
<li>Will the output images always be of same size?</li>
</ol>

<p>Cheers,
Gert</p>

python image numpy crop