与python匹配的Scipy方法

与python匹配的Scipy方法,python,numpy,image-processing,scipy,correlation,Python,Numpy,Image Processing,Scipy,Correlation,我想让这段代码更快,因为对于一个窗口大小为10x10的1000x1000图像,需要约4毫秒的时间 import numpy import scipy.misc from matplotlib import pyplot as plt import time def corr(a, b): '''finds the correlation of 2 intensities''' return (sum2(a,b)/(sum2(a,a)*sum2(b,b))**0.5) def

我想让这段代码更快,因为对于一个窗口大小为10x10的1000x1000图像,需要约4毫秒的时间

import numpy
import scipy.misc
from matplotlib import pyplot as plt
import time

def corr(a, b):
    '''finds the correlation of 2 intensities'''
    return (sum2(a,b)/(sum2(a,a)*sum2(b,b))**0.5)

def sum2(a,b):
    s = 0
    for x in range(len(a)):
        s += a[x]*b[x]
    return s

##the commented code displays the images     
##plt.ion()
def find_same(img1,img2,startx,width,starty,hight):
    '''inputs 2 filenames, startx, width of search window, and hight.'''     
    crop_img = img1[starty:(starty+hight),startx:(startx+width)]
    plt.imshow(crop_img,interpolation='nearest')
    plt.draw()
    a = []
    for x in numpy.nditer(crop_img): #converting image to array of intesities
        a.append(float(x))     
    mcfinder = []
    for x in range(img2.shape[1]-width):
        finder = img2[starty:(starty+hight),x:(x+width)]
        b = []
        for y in numpy.nditer(finder):
            b.append(float(y))
        correl = corr(a,b) #find correlation
        mcfinder.append(correl)
    maxim = max(mcfinder)
    place = mcfinder.index(maxim)
    finder = img2[starty:(starty+hight),place:(place+width)]
##    plt.imshow(finder,interpolation='nearest')
##    plt.draw()
##    time.sleep(1)
##    plt.close()
    return maxim,place

img1 = scipy.misc.imread('me1.bmp')
img2 = scipy.misc.imread('me2.bmp')
starttime = time.clock()
print find_same(img1,img2,210,40,200,40)
endtime = time.clock()
print endtime-starttime
有没有办法让这更快?还是我这样做根本是错误的?
请让我知道。要运行它,您需要matplotlib、scipy和numpy。

[我没有名声将此作为评论发布]

正如@cel的评论中提到的,您应该只使用numpy操作而不是列表上的循环来对代码进行矢量化

似乎您正在尝试进行一些模板匹配,您是否查看了scikit图像文档中的for
skimage.feature.match_template()
?scikit image还提供了numpy数组的窗口视图(
skimage.util.view-as-windows()
),在逐块分析numpy数组时非常方便


如果不想添加另一个依赖项,则应使用Scipy的特殊函数为您计算相关性,例如
Scipy.ndimage.filters.correlate()
(同时查看中的其他函数)。

是,我非常确信,通过完全用numpy编写并避免不必要的for循环,您可以将其速度提高至少一个数量级。因为您已经有了工作代码,这可能是一个很好的候选代码。如果您决定在那里发布,请查看有关如何在代码审阅中发布的说明。