[英]How do I interpolate a 2D gridded point cloud to a continuous area?
我有一個2維Numpy NDarray填充0到8之間的浮點數。這個2維數組大小是(1000, 1600)
1000,1600 (1000, 1600)
,有大約1400個值,(點雲中的點),其余值是None
,所以matplotlib不會繪制這些值。 您可以在下圖中看到繪制的表格。 我想要的是,使用旁邊的值插值的None值具有漸變式熱圖。 這個pointcloud代表屋頂的形狀,我想把這個數據處理成一個我可以提供給神經網絡以檢測屋頂類型的圖像。
我用於此圖的代碼很短,
import matplotlib.pyplot as plt
plt.clf()
#plotGrid is the numpy.ndarray with shape (1000, 1600) and dtype float
plt.imshow(plotGrid, cmap='gray', interpolation='nearest')
plt.colorbar()
plt.show()
tricontourf
您可以使用tricontour
/ tricontourf
圖。 為此,您首先需要過濾掉所有的nan
值(您應該確實使用無效值np.nan
而不是None
)。 可以將這些值及其坐標放入plt.tricontourf()
以獲得等高線圖而無需手動插值。
import matplotlib.pyplot as plt
import numpy as np
# Generate some example data
f = lambda x,y : np.exp((-(x-150)**2-(y-150)**2)/3.e3)
plotGrid = np.zeros((300,300))*np.nan
coo = np.random.randint(5,295, size=(150,2) )
for x,y in coo:
plotGrid[y,x] = f(x,y)
#plotGrid is now a numpy.ndarray with shape (300,300), mostly np.nan, and dtype float
# filter out nan values and get coordinates.
x,y = np.indices(plotGrid.shape)
x,y,z = x[~np.isnan(plotGrid)], y[~np.isnan(plotGrid)], plotGrid[~np.isnan(plotGrid)]
plt.tricontourf(x,y,z)
plt.colorbar()
plt.show()
tripcolor
使用tripcolor
是另一種選擇:
plt.tripcolor(x,y,z, shading='gouraud')
contourf
您還可以先使用matplotlib.mlab.griddata
在網格上插入數據,然后使用正常的contourf
圖,
xi = np.linspace(0, plotGrid.shape[1], plotGrid.shape[1])
yi = np.linspace(0, plotGrid.shape[0], plotGrid.shape[0])
zi = mlab.griddata(x, y, z, xi, yi, interp='linear')
plt.contourf(xi, yi, zi, 15)
imshow
或者以同樣的方式使用imshow
情節,
plt.imshow(zi)
我認為scipy.interpolate.interp2d
您的需求:
import scipy.interpolate
z_all = plotGrid.astype(float) # convert nones to nan
x_all, y_all = np.indices(plotGrid.shape) # get x and y coordinates
# convert to 1d arrays of coordinates
valid = ~np.isnan(z_all)
x, y, z = x_all[valid], y_all[valid], z_all[valid]
# interpolate
interp = scipy.interpolate.interp2d(x, y, z)
filled_data = interp(x_all[:,0], y_all[0,:]) # this is kinda gross, but `interp` doesn't
# do normal broadcasting
plt.imshow(filled_data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.