Searching a sub-array inside a 2D array (image recognition)

arrays, image-recognition, numpy, python, search

Solution

How about this solution:

1) Identify all the locations of the upper-right left-hand element of the small array in the big array.

2) Check if the slice of the big array that corresponds to a every given element is exactly the same as the small array.

Say if the upper left-hand corner element of the slice is 5, we would find locations of 5 in the big array, and then go check if a slice of the big array to the bottom-left of 5 is the same as small array.

import numpy as np

a = np.array([[0,1,5,6,7],
              [0,4,5,6,8],
              [2,3,5,7,9]])

b = np.array([[5,6],
              [5,7]])

b2 = np.array([[6,7],
               [6,8],
               [7,9]])

def check(a, b, upper_left):
    ul_row = upper_left[0]
    ul_col = upper_left[1]
    b_rows, b_cols = b.shape
    a_slice = a[ul_row : ul_row + b_rows, :][:, ul_col : ul_col + b_cols]
    if a_slice.shape != b.shape:
        return False
    return (a_slice == b).all()

def find_slice(big_array, small_array):
    upper_left = np.argwhere(big_array == small_array[0,0])
    for ul in upper_left:
        if check(big_array, small_array, ul):
            return True
    else:
        return False

Result:

>>> find_slice(a, b)
True
>>> find_slice(a, b2)
True
>>> find_slice(a, np.array([[5,6], [5,8]]))
False

Problem

Essentially, I have a numpy image array and I'm trying to find if it contains a 2x2 block of particular RGB pixel values. So, for example, if my (simplified) image array was something like: ``` A B C D E F G H I J K L M N O P Q R S T U V W X ``` I am trying to check if it contains, say: ``` J K P Q ``` I'm pretty new to numpy so I'd appreciate any help on this, thanks.

Original source