如何优化 numpy 均值 window

How to optimize numpy mean window

我正在尝试获取一个新的光栅,循环遍历所有数组并使用搜索 window 25x25 像素。我想知道你是否知道更好的方法来做到这一点,因为我的方法需要太多时间。

import sys
import os
import numpy as np
import math

from osgeo import gdal, osr, gdal_array, gdalnumeric
from osgeo.gdalnumeric import *

numpy.warnings.filterwarnings('ignore')

def mean_neighbors(M,x,y,w=1):
    l = []
    for i in range(max(0,x-w), x+(w+1)):
        for j in range(max(0,y-w), y+(w+1)):
            try:
                t = M[i][j]
                l.append(t)
            except IndexError:
                pass
    return np.mean(l)

raster_file = gdal.Open('image.tif', gdal.GA_ReadOnly)
rst         = gdalnumeric.BandReadAsArray(raster_file.GetRasterBand(1))

cob = np.zeros(rst.shape)

for i in range(rst.shape[0]):
    for j in range(rst.shape[1]):
        cob[i][j] = mean_neighbors(rst, i, j, 25) # want to optimize this function

移动window意思是一个很常见的函数,你应该不需要自己写。您可以使用以下两个快速实现: