Improving performance of a Python function that outputs the pixels that are different between two images

Viewed 152

I'm working on a computer vision project and am looking to build a fast function that compares two images and outputs only the pixels where the differences between the pixels of the two images are sufficiently different. Other pixels get set to (0,0,0). In practice, I want the camera to detect objects and ignore the background.

My issue is the function doesn't run fast enough. What are some ways to speed things up?

def get_diff_image(fixed_image): 
    #get new image
    new_image = current_image()

    #get diff
    diff = abs(fixed_image-new_image)

    #creating a filter array 
    filter_array = np.empty(shape = (fixed_image.shape[0], fixed_image.shape[1]))
    for idx, row in enumerate(diff):
        for idx2, pixel in enumerate(row):
            mag = np.linalg.norm(pixel)
            if mag > 40:
                filter_array[idx][idx2] = True
            else:
                filter_array[idx][idx2] = False

    #applying filter
    filter_image = np.copy(new_image)
    filter_image[filter_array == False] = [0, 0, 0]
    return filter_image
3 Answers
Related