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]]