编程语言
首页 > 编程语言> > python – 在2D数组中搜索子数组(图像识别)

python – 在2D数组中搜索子数组(图像识别)

作者:互联网

本质上,我有一个numpy图像数组,我试图找到它是否包含特定RGB像素值的2×2块.因此,例如,如果我的(简化)图像数组是这样的:

A B C D E F

G H I J K L

M N O P Q R

S T U V W X

我试图检查它是否包含,说:

J K

P Q

我很擅长numpy,所以我很感激任何帮助,谢谢.

解决方法:

这个解决方案怎么样:

1)识别大数组中小数组的右上角左侧元素的所有位置.

2)检查对应于每个给定元素的大数组的切片是否与小数组完全相同.

假设切片的左上角元素是5,我们会在大数组中找到5的位置,然后去检查5的左下角的大数组切片是否与小数组相同.

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

标签:python,arrays,search,numpy,image-recognition
来源: https://codeday.me/bug/20190629/1325917.html