优化性能以计算两个图像之间的欧式距离

wod*_*dzu 3 python algorithm image-processing matrix euclidean-distance

我在python中实现了k-nearest-neighbours算法,以对mnist数据库中随机选择的图像进行分类。但是,我发现距离函数非常慢:将10个测试图像的analisys与10k图像的训练集进行对比大约需要2分钟。图像的分辨率为28x28像素。由于我是python的新手,所以我觉得这可能会更快。该函数应该用于计算两个相同大小的灰度图像之间的欧式距离。

def calculateDistance(image1, image2):
    distance = 0
    for i in range(len(image1)):
        for j in range(len(image1)):
            distance += math.pow((image1[i][j]-image2[i][j]),2)
    distance = numpy.sqrt(distance)
    return distance
Run Code Online (Sandbox Code Playgroud)

Nik*_* B. 5

如果使用numpy数组表示图像,则可以改用以下内容:

def calculateDistance(i1, i2):
    return numpy.sum((i1-i2)**2)
Run Code Online (Sandbox Code Playgroud)

这应该快得多,因为它使用快速的C实现进行繁重的工作。还可以考虑使用缓存不两次计算两个图像的差。