缩小时的值插值 [英] Interpolation of values when zooming down
问题描述
我有一个2D数组,我想下采样以将其与另一个数组进行比较.
I have a 2D array that I would like to down sample to compare it to another.
假设我的数组x
是512x512
,我想要一个数组y
128x128
,其中y
的元素是使用x
的overs 4x4
块的插值构建的>(此插值可能只是取平均值,但其他方法(例如几何平均值)可能会很有趣)
Lets say my array x
is 512x512
, I'd like an array y
128x128
where the elements of y
are build using an interpolation of the values overs 4x4
blocks of x
(this interpolation could just be taking the average, but other methodes, like geometric average, could be interesting)
到目前为止,我查看了scipy.ndimage.interpolation.zoom
,但没有得到想要的结果
So far I looked at scipy.ndimage.interpolation.zoom
but I don't get the results I want
>> x = np.arange(16).reshape(4,4)
>> print(x)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
>> y = scipy.ndimage.interpolation.zoom(x, 0.5)
>> print(y)
[[ 0 3]
[12 15]]
我希望y
是
[[ 2.5 4.5]
[10.5 12.5]]
请注意,仅设置dtype=np.float32
并不能解决问题...
Note that simply setting dtype=np.float32
doesn't solve that ...
推荐答案
您似乎要查找的是4块的均值,而zoom
无法获得,因为zoom
使用内插法(请参见docstring)
What you seem to be looking for is the mean over blocks of 4, which is not obtainable with zoom
, since zoom
uses interpolation (see its docstring)
要获取显示的内容,请尝试以下
To obtain what you show, try the following
import numpy as np
x = np.arange(16).reshape(4, 4)
xx = x.reshape(len(x) // 2, 2, x.shape[1] // 2, 2).transpose(0, 2, 1, 3).reshape(len(x) // 2, x.shape[1] // 2, -1).mean(-1)
print xx
这产生
[[ 2.5 4.5]
[ 10.5 12.5]]
或者,也可以使用sklearn.feature_extraction.image.extract_patches
from sklearn.feature_extraction.image import extract_patches
patches = extract_patches(x, patch_shape=(2, 2), extraction_step=(2, 2))
xx = patches.mean(-1).mean(-1)
print xx
但是,如果您的目标是以优美的方式对图像进行二次采样,则对图像的块进行均值并不是正确的方法:很可能会导致混叠效果.在这种情况下,您应该使用scipy.ndimage.gaussian_filter
(例如sigma=0.35 * subsample_factor
)稍微平滑图像,然后只需通过索引[::2, ::2]
However, if your goal is to subsample an image in a graceful way, then taking the mean over blocks of the image is not the right way to do it: It is likely to cause aliasing effects. What you should do in this case is smooth the image ever so slightly using scipy.ndimage.gaussian_filter
(e.g. sigma=0.35 * subsample_factor
) and then subsample simply by indexing [::2, ::2]
这篇关于缩小时的值插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!