Iterate over an array and save to a Dict

Asked

Viewed 45 times

0

Given that array:

array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)

I’m willing to stick it to count values on each line and then save them by line. The code below is doing the general sum. I would like to have the count per line.

def count(image):
    array = np.array(image)
    array[[ array == 0 ]] = 1
    array[[ array == 255 ]] = 0
    for row in array:
        unique, counts = np.unique(array[row,] , return_counts=True)
        d = dict(zip(unique, counts))
    return new

The result:

{0: 234710, 1: 515}

1 answer

0

Good morning, Your answer is almost correct, for your script to work you should put the unique only in row not in array[row,], also there is a row identifier, you can create a dictionary for each row, or a list at each position a dictionary for the corresponding row:

a list with a dictionary for each line:

def count(image):
    array = np.array(image)
    array[[ array == 0 ]] = 1
    array[[ array == 255 ]] = 0
    colecao = list()
    for row in array:
        unique, counts = np.unique(row , return_counts=True)
        d = dict(zip(unique, counts))
        colecao.append(d)

a dictionary for each line:

def count(image):
    array = np.array(image)
    array[[ array == 0 ]] = 1
    array[[ array == 255 ]] = 0
    count = 0
    colecao = dict()
    for row in array:
        unique, counts = np.unique(row , return_counts=True)
        d = dict(zip(unique, counts))
        colecao[count] = d
        count += 1

Check if any of them are useful to you.

  • I completed the first alternative with collection = [] at the beginning and Return(collection) at the end and it worked.

  • good that it worked out friend, if the answer helped her short and mark as answer, so help others answer their questions. Friend hugs.

Browser other questions tagged

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