搜索一个二维数组内的子阵列(图像识别) [英] Searching a sub-array inside a 2D array (image recognition)
问题描述
从本质上讲,我有一个numpy的图像阵列,我试图找到它是否包含特定的RGB像素值的2×2块。因此,举例来说,如果我(简体)图像阵列是这样的:
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
我是pretty新numpy的,所以我倒是AP preciate有这方面的帮助,谢谢。
I'm pretty new to numpy so I'd appreciate any help on this, thanks.
推荐答案
如何此解决方案:
1)确定的大阵列中的小阵列的右上左侧元件的所有位置。
1) Identify all the locations of the upper-right left-hand element of the small array in the big array.
2)检查对应于每个给定元件的大阵列的片是完全一样的小阵
2) Check if the slice of the big array that corresponds to a every given element is exactly the same as the small array.
说,如果切片的上左角元件是5,我们会发现的5个地点的大阵列中,然后转到判断是否大阵列的切片左下角5是相同的小数组。
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
结果:
>>> find_slice(a, b)
True
>>> find_slice(a, b2)
True
>>> find_slice(a, np.array([[5,6], [5,8]]))
False
这篇关于搜索一个二维数组内的子阵列(图像识别)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!