1

I have an array in which I want to recognize a certain pattern (template). As an example I took a small array to give an example, but in reality it is much larger and takes some time to perform operations. Is it possible to split this array into eg 2 parts and do these 2 at the same time using Multiprocessing to save time. And how would I best do this?

import numpy as np
from time import sleep, time

def find_match(array, template):
    template_1d = np.reshape(template, (1, 4))
    template_1d = np.squeeze(template_1d)
    matches = np.full_like(array, 0)
    row, col = array.shape

    start_row = 0
    start_col = 0

    # simulate delay:
    sleep(2)

    tolerance = 1
    for i in range(0, row):
        for j in range(0, col):
            try:
                arr = array[start_row: start_row+2, start_col: start_col+2]
                arr = np.reshape(arr, (1, 4))
                arr = np.squeeze(arr)
           
                correct = 0
                for a, b in zip(arr, template_1d):
                    if a <= b + tolerance and a >= b - tolerance:
                        correct += 1
                        if correct == 4:
                            matches[start_row: start_row+2, start_col: start_col+2] = 1
                            correct = 0

            except Exception as e:
                pass

            start_col += 1
        start_row += 1
        start_col = 0

    return matches


if __name__ == '__main__':
    array = np.array([[7, 0, 2, 2, 7, 7, 7],
                      [7, 3, 3, 5, 7, 7, 7],
                      [2, 1, 7, 7, 7, 7, 7],
                      [3, 3, 7, 7, 7, 7, 7]])

    template = np.array([[2, 1],
                         [3, 3]])

    start = time()
    matches = find_match(array, template)

    print("time: ", time() - start)
    print(matches)

output:

time:  2.0149645805358887
[[0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0]
 [1 1 0 0 0 0 0]
 [1 1 0 0 0 0 0]]
Kraigolas
  • 5,121
  • 3
  • 12
  • 37
  • [This question](https://stackoverflow.com/q/26896687/11659881) looks very similar to yours, where the answer claims that the problem is NP-complete (in general these problems are much more time consuming to solve). In that case, if you *could* use multiprocessing it may be beneficial. I suspect that if you could, the algorithm to split up your array and handle overlapping between splits would be non-trivial. However, is there some way you can get around finding the submatrix? What is the purpose of your search? Is the submatrix always going to be 2x2 or can it in general be any size? – Kraigolas Jan 30 '22 at 19:38
  • 1
    The array should actually represent a pixel image, and I want to recognize an object in it. The object (template) that I want to recognize usually has the same size (16x16 pixels and an array size of (16, 16)) –  Jan 30 '22 at 20:37

0 Answers0