Scipy interpolation how to resize/resample 3x3 matrix to 5x5?

时间秒杀一切 提交于 2019-11-30 08:59:40

Only two small problems:

1) Your xx,yy is outside the bounds of x,y (you can extrapolate, but I'm guessing you don't want to.)

2) Your sample size is too small for a kx and ky of 3 (default). Lower it to 2 and get a quadratic fit instead of cubic.

import numpy, scipy
from scipy import interpolate

kernelIn = numpy.array([
    [0,-2,0],
    [-2,11,-2],
    [0,-2,0]])

inKSize = len(kernelIn)
outKSize = 5

kernelOut = numpy.zeros((outKSize),numpy.uint8)

x = numpy.array([0,1,2])
y = numpy.array([0,1,2])

z = kernelIn

xx = numpy.linspace(x.min(),x.max(),outKSize)
yy = numpy.linspace(y.min(),y.max(),outKSize)

newKernel = interpolate.RectBivariateSpline(x,y,z, kx=2,ky=2)

kernelOut = newKernel(xx,yy)

print kernelOut
##[[  0.      -1.5     -2.      -1.5      0.    ]
## [ -1.5      5.4375   7.75     5.4375  -1.5   ]
## [ -2.       7.75    11.       7.75    -2.    ]
## [ -1.5      5.4375   7.75     5.4375  -1.5   ]
## [  0.      -1.5     -2.      -1.5      0.    ]]
Benjamin

If you are using scipy already, I think scipy.ndimage.interpolate.zoom can do what you need:

import numpy
import scipy.ndimage

a = numpy.array([[0.,-2.,0.], [-2.,11.,-2.], [0.,-2.,0.]])
out = numpy.round(scipy.ndimage.interpolation.zoom(input=a, zoom=(5./3), order = 2),1)

print out
#[[  0.   -1.   -2.   -1.    0. ]
# [ -1.    1.8   4.5   1.8  -1. ]
# [ -2.    4.5  11.    4.5  -2. ]
# [ -1.    1.8   4.5   1.8  -1. ]
# [  0.   -1.   -2.   -1.    0. ]]

Here the "zoom factor" is 5./3 because we are going from a 3x3 array to a 5x5 array. If you read the docs, it says that you can also specify the zoom factor independently for the two axes, which means you can upscale non-square matrices as well. By default, it uses third order spline interpolation, which I am not sure is best.

I tried it on some images and it works nicely.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!