随机数据的规则网格插值

2024-04-23 08:16:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据是这样的 Data

我想把它插值到一个4单元的网格上。每个单元格将只包含其内部所有点的平均值。enter image description here

输出应该是这样的

enter image description here

因此,我们将整个数据转换为2x2矩阵。此矩阵的每个单元格将具有其内部所有点的平均x坐标和平均y坐标值。在

A1=(3,-3);A2=(3.5,1.5)

A3=(-1,-3);A4=(-2,1)

我尝试了什么=====

avg = [[
        (
            ( mat[row][col][0]
            + mat[row][col+1][0]
            + mat[row+1][col][0]
            + mat[row+1][col+1][0] ) / 4.0
        , 
            ( mat[row][col][1]
            + mat[row][col+1][1]
            + mat[row+1][col][1]
            + mat[row+1][col+1][1] ) / 4.0
        )
        for col in range(0, len(mat[0]), 2) ]
    for row in range(0, len(mat), 2)
]

Tags: 数据in网格forlena1range矩阵
1条回答
网友
1楼 · 发布于 2024-04-23 08:16:31

我对numpy/scipy不太在行,我认为这在优雅和效率方面可以得到极大的改进,但它确实有效:

-> jupyter notebook with intermediate plots

最终代码:

import numpy as np
import matplotlib.pyplot as plt
import math
data = np.random.uniform(low=-2.0, high=2.0, size=(2,100))
dataX = data[0]
dataY = data[1]

#plot the data
plt.plot(data[0], data[1], 'b+')

gridSize = 1.0

# grid coordinates are lower left point of grid rectangles
gridMaxX = math.floor(max(dataX) / gridSize)
gridMaxY = math.floor(max(dataY) / gridSize)
gridMinX = math.floor(min(dataX) / gridSize)
gridMinY = math.floor(min(dataY) / gridSize)

gridX = np.arange(gridMinX,gridMaxX + gridSize, gridSize)
gridY = np.arange(gridMinY,gridMaxY + gridSize, gridSize)

#plot the grid
for ix, x in enumerate(gridX):
    plt.axvline(x=x)
for iy, y in enumerate(gridY): 
    plt.axhline(y=y)

#iterate the grid
for gridPosX in gridX:
    for gridPosY in gridY:
        inCell = lambda x,y: (gridPosX<x and x<gridPosX+gridSize 
                              and gridPosY<y and y<gridPosY+gridSize)

        pointsInCell = [ (x,y) for (x,y) in zip(dataX, dataY) if inCell(x,y)]
        if len(pointsInCell) > 0:
            xPos, yPos = zip(*pointsInCell)
            plt.plot(np.mean(xPos), np.mean(yPos), 'ro')
plt.show()

相关问题 更多 >