mercredi 24 février 2021

Find small matrix inside a bigger one but don't know how, in python (image attached)

I have a pattern that I have represented as a list of lists, and also tried as an array using numpy, and I have to find how many times this pattern exists within the bigger one, like this image

here In this cas it would be three times : Any ideas on how to solve?

Thanks!

(My code)

So far I have done this, but not even sure I am in the right direction. seems too complicated.

#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

Aucun commentaire:

Enregistrer un commentaire