def trim(image, shape):
"""
Trim image to a given shape
Parameters
----------
image: 2D `numpy.ndarray`
Input image
shape: tuple of int
Desired output shape of the image
Returns
-------
new_image: 2D `numpy.ndarray`
Input image trimmed
"""
shape = np.asarray(shape, dtype=int)
imshape = np.asarray(image.shape, dtype=int)
if np.alltrue(imshape == shape):
return image
if np.any(shape <= 0):
raise ValueError("TRIM: null or negative shape given")
dshape = imshape - shape
if np.any(dshape < 0):
raise ValueError("TRIM: target size bigger than source one")
if np.any(dshape % 2 != 0):
raise ValueError("TRIM: source and target shapes "
"have different parity")
idx, idy = np.indices(shape)
offx, offy = dshape // 2
return image[idx + offx, idy + offy]
评论列表
文章目录