我最后写了一个小函数,使用scipy.ndimage.zoom升级图像,但是为了缩小它,它首先将它升级为原始形状的倍数,然后通过块平均缩小.它接受scipy.zoom的任何其他关键字参数(order和prefilter)
我仍在寻找使用可用软件包的更清洁的解决方案.
def zoomArray(inArray, finalShape, sameSum=False, **zoomKwargs):
inArray = np.asarray(inArray, dtype = np.double)
inShape = inArray.shape
assert len(inShape) == len(finalShape)
mults = []
for i in range(len(inShape)):
if finalShape[i] < inShape[i]:
mults.append(int(np.ceil(inShape[i]/finalShape[i])))
else:
mults.append(1)
tempShape = tuple([i * j for i,j in zip(finalShape, mults)])
zoomMultipliers = np.array(tempShape) / np.array(inShape) + 0.0000001
rescaled = zoom(inArray, zoomMultipliers, **zoomKwargs)
for ind, mult in enumerate(mults):
if mult != 1:
sh = list(rescaled.shape)
assert sh[ind] % mult == 0
newshape = sh[:ind] + [sh[ind] / mult, mult] + sh[ind+1:]
rescaled.shape = newshape
rescaled = np.mean(rescaled, axis = ind+1)
assert rescaled.shape == finalShape
if sameSum:
extraSize = np.prod(finalShape) / np.prod(inShape)
rescaled /= extraSize
return rescaled