首页 > 解决方案 > How to optimize numpy mean window

问题描述

I'm trying to get a new raster making looping through all array and using a search window 25x25 pixels. I wonder if you know a better way to do this because it takes too much time with my approach.

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

标签: pythonnumpygdal

解决方案


Moving window mean is a very common function that you should not need to write yourself. Here are two fast implementations you can use:


推荐阅读