Issue
I'm trying to find the starting coordinates of a small 2D array (b) in a large numpy 2D array (a), I've written this method but it's too complicated and slow, does anyone have a better idea?
a=[[5 4 5 9 3 4 6 2 5 3]
[8 3 5 4 3 4 5 8 4 4]
[5 7 8 5 2 3 3 6 8 8]
[4 5 6 2 6 5 6 7 9 3]
[3 6 8 2 8 7 3 8 8 8]]
b=[[2 3 3]
[6 5 6]]
def screen_match(img1,img2):
match_1=list(img1.T[1])
img_len=len(match_1)
# img2=img2.tolist()
is_match=False
position=[]
for i in range(img2.shape[1]):
img2_col=img2[:, i].tolist()
for j in range(len(img2_col)):
img2_cut=img2_col[j:j+img_len]
if match_1== img2_cut:
inner_col=i+1
for m in range(2,img1.shape[1]):
inner_img1 = list(img1.T[m])
for n in range(i+1,img2.shape[1]):
inner_img2_col = img2[:, inner_col].tolist()
inner_img2_cut = inner_img2_col[j:j + img_len]
if inner_img1==inner_img2_cut:
is_match=True
break
else:
is_match=False
break
inner_col += 1
if not is_match:break
if is_match:
position=[i,j]
break
if is_match:break
if is_match:
print(position)
break
return position
Solution
You can use fancy indexing to reduce the number of nested loops
# Rename variables for clarity
array = a
kernel = b
array_H, array_W = array.shape
kernel_H, kernel_W = kernel.shape
def search_array():
for x in range(0,array_W-kernel_W):
for y in range(0,array_H-kernel_H):
array_subsection = array[y:y+kernel_H, x:x+kernel_W]
if array_subection == kernel:
print(f"kernel was found at x={x}, y={y}.")
return
print(f"kernel was not found in array.")
search_array()
Answered By - Michael Sohnen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.