python - Scikit-image:如何忽略/屏蔽来自 ndarray 的零值以便之后进行插值?

标签 python python-3.x scikit-image

正如您在上面看到的我的问题,我想屏蔽/忽略 ndarray 中的零值,我想在之后对其进行插值。我希望你能帮我解决这个问题,因为我已经尝试了很多天来解决这个问题。

我想要什么?

我有许多长度不同的 ndarray,我想对它们进行插值,让我们说在这种情况下,以使其更小。

这是其中一个数组的样子:

[0.0, 0.0, 0.0, 0.0, 0.0, 144.0, 144.0, 145.0, 145.0, 144.0, 143.0, 143.0, 0.0, 0.0, 0.0]

如你所见,它总是一行(我们称之为“array_row”),有很多元素(对于这个例子我只是写了一个有 15 个元素的数组例子)

我如何插值?

我正在使用 scikit-image resize 方法,像这样:

new_array = skimage.transform.resize(array_row, (1, 10))

这个插值的结果看起来像这样:

[0.0, 0.0, 71.49999999, 144.0, 144.60344827, 145.0, 144.70896278, 143.0, 71.49999999, 0.0, 0.0]

当使用插值时,这个结果是这样的。值“71.49999999”是因为非零值之前和/或之后的零值,这是正常的。

但就我而言,我不希望发生这种情况。我想让 skimage.transform.resize 忽略零值,这样结果会是这样的:

[0.0, 0.0, 144.0, 144.0, 144.60344827, 145.0, 144.70896278, 143.0, 143.0, 0.0, 0.0]

不应更改这些值(或至少只能从旁边的非零值开始)。

我实际上不知道该怎么做。我尝试了一些类似掩码的方法,并为被掩码的索引赋予值“255”,这也没有给出预期的结果。

您知道如何实现这个目标吗?

最佳答案

scikit-image 函数需要一个规则间隔的值网格,但 scipy 中还有其他插值器允许更多的自由。例如,考虑一个三次插值器,它将输入坐标和值作为输入:

import numpy as np
from scipy import interpolate

import matplotlib.pyplot as plt


y = np.array([150, 0.0, 0.0, 0.0, 0.0, 144.0, 144.0, 145.0, 145.0, 144.0, 143.0, 143.0, 0.0, 0.0, 148])
x = np.arange(len(y))
x_ = np.linspace(0, 14, 100)
mask = (y != 0)

p = interpolate.interp1d(x, y, kind='cubic')
p_masked = interpolate.interp1d(x[mask], y[mask], kind='cubic')

plt.plot(x, y, 'x-', label='Input')
plt.plot(x_, p(x_), label='Interpolated')
plt.plot(x_, p_masked(x_), label='Interpolated (ignoring zeros)')
plt.legend()
plt.savefig('/tmp/cubic_interpolation.png', dpi=300)
plt.show()

cubic interpolation with and without masking

对于这种方法,您需要指定端点,因为它不进行外推。径向基函数更适合外推,但在没有数据的区域也倾向于回落到零。

关于python - Scikit-image:如何忽略/屏蔽来自 ndarray 的零值以便之后进行插值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53855661/

相关文章:

javascript - 如何在 Python Selenium 中输入自动填充的文本字段

python - 在管理页面查看相册中的照片

python - 背景中的多种颜色(过渡)

python - Python 求和递归教程

python - 如何将在 scikit-image find_contours 中创建的轮廓导出到 shapefile 或 geojson?

python - Bash 脚本与用于 Shell-Command-Heavy 实用程序的 Python 脚本的优点

android - 我的 android 应用程序无法从 python 接收 fcm 消息

python - 如何在给定相对 bbox 坐标的情况下在此图片上裁剪车号?

numpy - 将图像格式从32FC1转换为16UC1

python - 断言错误 : `HyperlinkedIdentityField` requires the request in the serializer context