【问题标题】:Find small matrix inside a bigger one but don't know how, in python (image attached)在 python 中找到更大的矩阵中的小矩阵,但不知道如何(附图)
【发布时间】:2021-02-24 12:58:13
【问题描述】:

我有一个模式,我用列表的列表表示,也尝试使用 numpy 作为数组,我必须找出这个模式在更大的模式中存在多少次,比如这张图片

here 在这种情况下,它将是三倍: 关于如何解决的任何想法?

谢谢!

(我的代码)

到目前为止,我已经这样做了,但我什至不确定我的方向是否正确。好像太复杂了。

#Defined both pattern and bigger matrix as a list of lists.

imagen_1 = [[0, 0, 1, 0, 0],
         [1, 1, 1, 1, 1],
         [0, 1, 1, 1, 0],
         [1, 1, 0, 1, 1],
         [1, 0, 0, 0, 1]]

imagen_2 = [[1, 1],
         [0, 1]]


# Then tried this logic, but got too complicated to loop.
# At this point I am just trying to check the actual position and the nearest to the right

def repeticiones(original, patron):
 
 if len(patron) > len(original) or len(patron[0]) > len(original[0]):
     raise ValueError(f"La imagen patrón es más grande que la original. Por favor, proporcione una imagen patrón más pequeña a {len(original)} * {len(original[0])}")
 
 c = 0
 
 filas_patron = len(patron)
 columnas_patron = len(patron[0])
 
 j = -1
 i = -1
 
 for linea in range((filas_patron)-2):
     j += 1
     i = -1
     for columna in range((columnas_patron)-2):
         i += 1
         igual = original[j][i]==patron[0][0] and linea[j][i+1]==patron[0][2]
         if igual:
             return True
     
 return False

【问题讨论】:

  • 到目前为止你尝试过什么?请发布您的代码。
  • 假设 A 是你的 numpy 矩阵。然后使用此条件if(A[x][y]==1 & A[x][y+1]==1 & A[x+1][y]==0 & A[x+1][y+1]==1) 给出 x 和 y 所需的限制并尝试。这只是一个想法,因为我没有你的代码。

标签: python algorithm numpy matrix design-patterns


【解决方案1】:

这很简单,只需进行网格搜索并将子矩阵与所需模式进行比较:

A = np.random.randint(0, 2, size=(10, 12))
P = np.array([[1, 1],
              [0, 0]])
n = 0
for i in range(A.shape[0] - P.shape[0]):
    for j in range(A.shape[1] - P.shape[1]):
        n += np.all(A[i:(i+P.shape[0]), j:(j+P.shape[1])] == P)
print(f"Pattern 'P' found {n} times in 'A'.")

【讨论】:

  • 酷!但是我犯了一个错误并编辑了它。模式是 [[1, 1], [0, 1]] 我最初发布的内容。我现在正在尝试调整您的代码
  • 我什至不确定我是否必须更改代码,而不是定义更大的矩阵而不是随机化一个。使用模式和 A 矩阵提供它说找到 2 次​​span>
  • 使用更新版本更新您的代码以检查错误。
猜你喜欢
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 2013-04-26
  • 2020-11-18
相关资源
最近更新 更多