mos*_*ski 10 python interpolation numpy scipy resampling
编辑:保罗在下面解决了这个问题.谢谢!
我正在尝试将3x3矩阵重新采样(升级)为5x5,使用interpolate.interp2d或interpolate.RectBivariateSpline(或其他任何工作)填充中间点.
如果有一个简单的现有函数来执行此操作,我想使用它,但我还没有找到它.例如,一个函数可以像:
# upscale 2x2 to 4x4
matrixSmall = ([[-1,8],[3,5]])
matrixBig = matrixSmall.resample(4,4,cubic)
Run Code Online (Sandbox Code Playgroud)
那么,如果我从一个3x3矩阵/数组开始:
0,-2,0
-2,11,-2
0,-2,0
Run Code Online (Sandbox Code Playgroud)
我想计算一个新的5x5矩阵("I"表示内插值):
0, I[1,0], -2, I[3,0], 0
I[0,1], I[1,1], I[2,1], I[3,1], I[4,1]
-2, I[1,2], 11, I[3,2], -2
I[0,3], I[1,3], I[2,3], I[3,3], I[4,3]
0, I[1,4], -2, I[3,4], 0
Run Code Online (Sandbox Code Playgroud)
我一直在搜索和阅读并尝试各种不同的测试代码,但我还没有弄清楚我正在尝试做什么的正确语法.我也不确定我是否需要在某些行中使用meshgrid,mgrid或linspace.
编辑:修复和工作感谢Paul
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,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
Run Code Online (Sandbox Code Playgroud)
只有两个小问题:
1)你的xx,yy超出x,y的范围(你可以推断,但我猜你不想.)
2)您的样本量太小,kx和ky为3(默认值).将它降低到2并得到二次拟合而不是立方.
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. ]]
Run Code Online (Sandbox Code Playgroud)
如果你已经使用scipy,我认为scipy.ndimage.interpolate.zoom可以做你需要的:
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. ]]
Run Code Online (Sandbox Code Playgroud)
这里的"缩放因子"是5./3因为我们从3x3阵列变为5x5阵列.如果您阅读文档,它表示您还可以为两个轴单独指定缩放系数,这意味着您也可以升级非方形矩阵.默认情况下,它使用三阶样条插值,我不确定是最好的.
我在一些图像上尝试过,它运行得很好.
| 归档时间: |
|
| 查看次数: |
9825 次 |
| 最近记录: |