我想沿第一個維度插入一個 3D 陣列。
就資料而言,這意味著我想在地理值中插入缺失時間,換句話說,讓這個影片稍微平滑一點:

我通過呼叫來做到這一點:
new = ma.apply_along_axis(func1d=masked_interpolation, axis=0, arr=dst_data, x=missing_bands, xp=known_bands)
其中插值函式如下:
def masked_interpolation(data, x, xp, propagate_mask=True):
import math
import numpy as np
import numpy.ma as ma
# The x-coordinates (missing times) at which to evaluate the interpolated values.
assert len(x) >= 1
# The x-coordinates (existing times) of the data points (where returns a tuple because each element of the tuple refers to a dimension.)
assert len(xp) >= 2
# The y-coordinates (value at existing times) of the data points, that is the valid entries
fp = np.take(data, xp)
assert len(fp) >= 2
# Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x.
new_y = np.interp(x, xp, fp.filled(np.nan))
# interpolate mask & apply to interpolated data
if propagate_mask:
new_mask = data.mask[:]
new_mask[new_mask] = 1
new_mask[~new_mask] = 0
# the mask y values at existing times
new_fp = np.take(new_mask, xp)
new_mask = np.interp(x, xp, new_fp)
new_y = np.ma.masked_array(new_y, new_mask > 0.5)
print(new_y) # ----> that seems legit
data[x] = new_y # ----> from here it goes wrong
return data
列印new_y時,插值看起來是一致的(分布在 [0,1] 區間,我想要的)。但是,當我列印最終輸出(new陣列)時,它肯定更平滑(更多條帶),但所有非屏蔽值都更改為 -0.1(沒有任何意義):

將其寫入光柵檔案的代碼是:
# Writing the new raster
meta = source.meta
meta.update({'count' : dst_shape[0] })
meta.update({'nodata' : source.nodata})
meta.update(fill_value = source.nodata)
assert new.shape == (meta['count'],meta['height'],meta['width'])
with rasterio.open(outputFile, "w", **meta) as dst:
dst.write(new.filled(fill_value=source.nodata))
uj5u.com熱心網友回復:
弄清楚這一點非常棘手。發生的情況是插值函式必須用 nan 填充,以便插值起作用,然后用有限值替換剩余的 nan(例如,當整個 fp 向量為 nan 時)。然后應用插值掩碼無論如何都會隱藏這些值。這是怎么回事:
def masked_interpolation(data, x, xp, propagate_mask=True):
import math
import numpy as np
import numpy.ma as ma
# The x-coordinates (missing times) at which to evaluate the interpolated values.
assert len(x) >= 1
# The x-coordinates (existing times) of the data points (where returns a tuple because each element of the tuple refers to a dimension.)
assert len(xp) >= 2
# The y-coordinates (value at existing times) of the data points, that is the valid entries
fp = np.take(data, xp)
assert len(fp) >= 2
# Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x.
new_y = np.interp(x, xp, fp.filled(np.nan))
np.nan_to_num(new_y, copy=False)
# interpolate mask & apply to interpolated data
if propagate_mask:
new_mask = data.mask[:]
new_mask[new_mask] = 1
new_mask[~new_mask] = 0
# the mask y values at existing times
new_fp = np.take(new_mask, xp)
new_mask = np.interp(x, xp, new_fp)
new_y = np.ma.masked_array(new_y, new_mask > 0.5)
data[x] = new_y
return data
導致:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449890.html
