Array always getting the same value [Loop in two matrices simultaneously]

Asked

Viewed 85 times

3

My program scans an image and assigns color values R,G, B the variables that were compared with matrices containing the colors R,G, B asphalt and earth called auxAsfalto and auxTerra. The point is, when I go through the picture in the position i, j, that are the pixels of horizontal and vertical, everything occurs normal, but when I go through the matrices that have the values of color of asphalt and earth occurs two errors: first the for running through the asphalt color matrix does not leave the 0 position. Already the 2nd for that runs through the earth color matrix always returns the the first row of the matrix. That is, the repeating structures are not working. Thanks in advance.

Follow the code snippet:

for i in range(img.shape[1]): #percorre a linha
    for j in range(img.shape[0]): #percorre a coluna
        auxCor = img[i,j]
        for k in range(len(corAsfalto)): #percorre a matriz corAsfalto
            auxAsfalto = corAsfalto[k]
            print("TESTE auxAsfalto: {}".format(auxAsfalto))
            if np.all(auxAsfalto) == np.all(auxCor): #verifica se as cores são iguais
                print("Cor de Asfalto em auxAsfalto: {}".format(auxCor))
                contAsfalto +=1
                break
            else:
                print("Não possui asfalto")
                break
        for l in range(len(corTerra)): #percorre a matriz corTerra
            auxTerra = corTerra[l]
            print("TeSTe auxTerra: {}".format(auxTerra))
            if np.all(auxTerra) == np.all(auxCor): #verifica se as cores são iguais
                print("Cor terra em auxCor: {}, cor Terra em auxTerra: {}".format(auxCor, auxTerra))
                contTerra += 1
                break
            else:
                break

    print("Quantidade de pixels de asfalto: %d"%contAsfalto)
    print("Quantidade de pixels de terra: %d"%contTerra)
    print("Quantidade de pixels da imagem: %d"%qntPixels)

Return:

Cor terra em auxCor: [132 136 117], cor Terra em auxTerra: [128.  105.1  98.9]
TESTE auxAsfalto: [154.  172.1 173.9]
Cor de Asfalto em auxAsfalto: [141 147 128]
TeSTe auxTerra: [128.  105.1  98.9]
Cor terra em auxCor: [141 147 128], cor Terra em auxTerra: [128.  105.1  98.9]
TESTE auxAsfalto: [154.  172.1 173.9]
Cor de Asfalto em auxAsfalto: [153 159 140]
TeSTe auxTerra: [128.  105.1  98.9]

1 answer

3


From what I understand your "matrices" are common image matrices that have the format (n, n, 3) correct? and Oce wants to compare the occurrences of the RGB channels within them, right? Since you didn’t create one complete and verifiable example, to understand the context, I created one, see if it’s what you want:

TL;DR

import numpy as np

# Criação das imagens:
img_terra = np.random.randint(222, size=(10, 10,3)) 
img_asfalto = np.random.randint(222, size=(10, 10,3))

# Forçando uma igualdade
img_terra[5] = img_asfalto[5]

# Comparando as ocorrencias nas imagens:
for im1, im2 in zip(img_asfalto, img_terra):
    if np.array_equal(im1,im2):
        ln = '*'*18
        print(ln,'Ocorrencias iguais',ln, sep='\n')
    else:
        print('ocorrencias diferentes:')
        '''
        #(1) Aqui voce pode usar um outro for com zip para 
        tratar cada elemento nas duas ocorencias:
        '''    
else:
    print("Melhor do que 'for' aninhados. :-)")   

In the middle of the code where I wrote down #(1) Voce could do the treatment you want/need with each element of the two images when the occurrences are different, for example, something like:

for e1, e2 in zip(im1,im2):
    # Process
    # ... 
    pass

See working on repl it.

Edited (as per comment)
Example with the zip

lst1  = [1, 2, 3]
lst2  = ['A', 2, 'B']
zipped = list(zip(lst1,lst2))  
print(zipped)

The output is a list of tuples with the pairs of elements of the two lists:

[(1, 'A'), (2, 2), (3, 'B')] # Lista de tuplas

Comparing the elements of the two lists:

for e1, e2 in zip(lst1, lst2):
    if e1==e2:
        idx = lst1.index(e1)
        print('elemento:',idx, 'de lst1 é igual ao elemento', idx, 'de lst2')

Exit:

elemento 1 de lst1 é igual ao elemento 1 de lst2
  • I’m a beginner in python, and from what I understand the zip takes each position that is equal of the two matrices and creates another matrix with the position elements of each array, right? So in this case all that bit of code that I did can be summed up to this?

  • Actually zip creates an iterator that aggregates the two matrices, it’s like a function to join the two matrices, I’m editing the answer and adding an example with the zip.

  • Got it, it helped me a lot. Thank you very much!! :)

  • Consider giving the acceptance and an upvote (if you didn’t do it) in response. :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.