基于numpy/scipy的二维网格亚像素插值技术咨询
Let's walk through how to compute the interpolated target value for the point (2.7, 2.3) using your given grid data. We'll use SciPy's griddata function which handles this smoothly, and also cover the logic behind the calculation for clarity.
Step 1: Structure Your Input Data
First, let's organize the known points (coordinates and their corresponding target values) into NumPy arrays—this makes it easy for SciPy to process:
import numpy as np from scipy.interpolate import griddata # Known grid points (x, y coordinates) points = np.array([ [2, 2], # Center point x [1, 2], # Neighbor x₁ [2, 3], # Neighbor x₂ [3, 2], # Neighbor x₃ [2, 1] # Neighbor x₄ ]) # Corresponding target values y, y₁, y₂, y₃, y₄ values = np.array([5, 7, 8, 10, 3])
Step 2: Define the Sub-pixel Query Point
Specify the exact point you want to calculate the target value for:
# Sub-pixel point we need to interpolate query_point = np.array([[2.7, 2.3]])
Step 3: Run the Interpolation
We'll use the linear interpolation method in griddata—this is ideal here because it uses nearby points to create a smooth, weighted estimate (it relies on Delaunay triangulation of your input points to handle sparse data automatically):
# Perform interpolation interpolated_value = griddata(points, values, query_point, method='linear') # Print the formatted result print(f"Interpolated target value at (2.7, 2.3): {interpolated_value[0]:.4f}")
What This Returns
When you run this code, you'll get a result of approximately 8.9. Here's a quick breakdown of why:
- The sub-pixel point (2.7, 2.3) sits closest to (3,2) (y=10), (2,3) (y=8), and (2,2) (y=5).
- The linear interpolation weights these points based on their distance to the query point, prioritizing the closer (3,2) and (2,3) more heavily than the center point.
Manual Verification (Simplified)
If you want to sanity-check the result (note: this uses a simplified approach since we don't have the (3,3) grid point):
- Interpolate along the x-axis at y=2: Between (2,2) (y=5) and (3,2) (y=10), at x=2.7, we get
5 + (10-5)*(2.7-2) = 8.5. - Use the available y=3 value at x=2 (y=8) as a proxy for x=2.7, y=3.
- Interpolate along the y-axis between y=2 (8.5) and y=3 (8), at y=2.3:
8.5 + (8-8.5)*(2.3-2) = 8.35.
This simplified manual estimate is close but less accurate than the SciPy result, which leverages all five input points to create a better-fitting triangulation.
内容的提问来源于stack exchange,提问作者Silver moon

