我正在尝试实施最短距离算法使用 GDAL 和 Python 进行图像分类。计算样本区域的平均像素值并将其存储到数组列表(“sample_array”)中后,我将图像读入名为“values”的数组中。使用以下代码循环遍历该数组:
values = valBD.ReadAsArray()
# loop through pixel columns
for X in range(0,XSize):
# loop thorugh pixel lines
for Y in range (0, YSize):
# initialize variables
minDist = 9999
# get minimum distance
for iSample in range (0, sample_count):
# dist = calc_distance(values[jPixel, iPixel], sample_array[iSample])
# computing minimum distance
iPixelVal = values[Y, X]
mean = sample_array[iSample]
dist = math.sqrt((iPixelVal - mean) * (iPixelVal - mean)) # only for testing
if dist < minDist:
minDist = dist
values[Y, X] = iSample
classBD.WriteArray(values, xoff=0, yoff=0)
对于大图像,此过程需要很长时间。这就是为什么我想问是否有人知道更快的方法。我不太了解 python 中不同变量的访问速度。或者也许有人知道我可以使用的图书馆。
提前致谢,
马里奥
您绝对应该使用 NumPy。我使用一些相当大的栅格数据集,NumPy 会烧毁它们。在我的机器上,使用下面的代码对于 1000 x 1000 阵列没有明显的延迟。代码后面有对其工作原理的解释。
import numpy as np
from scipy.spatial.distance import cdist
# some starter data
dim = (1000,1000)
values = np.random.randint(0, 10, dim)
# cdist will want 'samples' as a 2-d array
samples = np.array([1, 2, 3]).reshape(-1, 1)
# this could be a one-liner
# 'values' must have the same number of columns as 'samples'
mins = cdist(values.reshape(-1, 1), samples)
outvalues = mins.argmin(axis=1).reshape(dim)
cdist() http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html
计算与每个元素的“距离”values
到每个元素samples
。这会生成一个 1,000,000 x 3 数组,其中每一行n
与像素的距离n
原始数组中的每个样本值[1, 2, 3]
. argmin(axis=1)
为您提供每行最小值的索引,这就是您想要的。快速重塑可为您提供图像所需的矩形格式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)