python - 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
解决方案
Moving window mean is a very common function that you should not need to write yourself. Here are two fast implementations you can use:
推荐阅读
- r - 可以使用 dygraphs 按日/月而不是完整日期对象进行绘图吗?
- flutter - 颤振initState()与build()?
- javascript - 从 div id 加载 Google Maps 标记
- java - 如何从 WebElements 列表中获取元素的数量(大小)
- sql - 使用 A Union B 与 Where A OR B 的 Postgres 性能
- android - Android - 不使用 Intent 更新联系人
- mysql - MySQL 子选择然后组不工作
- javascript - Angular 在组件内嵌套哑组件并仅显示给特定页面或父组件
- java - 升级到 Java 8 会导致单元测试中的 Orika 映射器 java.io.IOException: invalid constant type: 15 at 142
- javascript - safari input type='number' 无法显示真实值