template matching: slow manual pixel access using integral image

asked 2013-04-21 09:15:29 -0500

AuroraPhields gravatar image

I am trying to do a sort of template matching that looks for dark blobs in my image. I am using a template of a black square surrounded by a white square as the template and running this image across all valid x,y in the image of concern. I thought that it would be much faster than using the template matching functions to use an integral image and collect data from only 8 points for every x,y that I want to check since eventually I need to do this check for multiple sizes of the template.

However, my code has been exceedingly slow, so I think that what I am doing is not compatible with how OpenCV/numpy store and access data. What is the fastest way to do this sort of matching? Is the way I'm accessing the pixels in the image manually with a for loop the problem?

I'm using OpenCV 2.4 with python 2.7 and importing numpy. I'm passing a binary 250x400 pixel image to the function and my code is below:

def estimate_pupil(img, r): # estimates the x,y position of the pupil in img # REALLY REALLY SLOW RIGHT NOW

    # create an integral image ii to do fast pupil location estimation
    ii = cv2.integral(img);

    h = img.shape[0];
    w = img.shape[1];

    best = 0;
    bestx = 0;
    besty = 0;
    # loop through all positions x,y
            for y in range(h-6*r-1):
                    for x in range(w-6*r-1):
                            #print "(x,y) is " + str(x) + " " + str(y);
                            bright = ii[y+6*r,x+6*r] - ii[y+6*r,x] - \
                                    ii[y,x+6*r] - ii[y,x];
                            i = x+2*r;
                            j = y+2*r;
                            dark = ii[j+r,i+r] - ii[j+r,i] - \
                                    ii[j,i+r] - ii[j,i];
                            matchval = 2*dark - bright;
                            if matchval > best:
                                    best = matchval;
                                    bestx = i + r;
                                    besty = j + r;

    return bestx, besty;
edit retag flag offensive close merge delete