一个python函数,用于提取网格图中的数据



我有以下代码和绘图:

import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
def func(x, y):
return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
grid_x, grid_y = np.mgrid[0:1:200j, 0:1:200j]
rng = np.random.default_rng()
points = rng.random((1000, 2))
values = func(points[:,0], points[:,1])
grid_z = griddata(points, values, (grid_x, grid_y), method='linear')
plt.xlabel("Degrees")
plt.ylabel("Degrees")
plt.imshow(grid_z, extent=(-0.5,0.5,-0.5,0.5), origin='lower')

我想提取以上图为中心的半径为0.25°的圆形区域内所有点的平均值。

感谢您的帮助

首先需要的是圆的布尔掩码。然后可以将其应用于grid_z,以隔离圆内的所有值并计算它们的平均值。

一种更好的方法是直接在grid_xgrid_y上使用掩码来仅在所需的点上插值函数。

# Compute the mask of a circle
center_grid_x = 0.5
center_grid_y = 0.5
radius = 0.25
mask = (grid_x - center_grid_x) ** 2 + (grid_y - center_grid_y) ** 2 < radius **2
# The mask can be visualized with 
# plt.imshow(mask)
# Apply the mask to grid_z and compute the mean
mean1 = np.mean(grid_z[mask])
# Or better compute only the values of points inside the circle
values_z = griddata(points, values, (grid_x[mask], grid_y[mask), method='linear')
mean2 = np.mean(values_z)

最新更新