Home > Back-end >  Nested for loop error (truth value ambiguous)
Nested for loop error (truth value ambiguous)

Time:06-26

I've got a matrix (array of arrays, denoted pixel_matrix) of values corresponding to pixel values of an image. I basically want to loop through it and change every value above 0 to a 1 so it's entirely binary values. Note, the matrix has thousands of values, hence the break between the start and end.

I've got this nested for loop but get this error message, anyone know a workaround?(See convert_to_boolean function)

1

CodePudding user response:

You need to use:

def convert_to_boolean(pixel_matrix):
    for column in pixel_matrix:
        for i in range(len(column)):
            if column[i] > 0:
                column[i] = 1
    return pixel_matrix

convert_to_boolean(pixel_matrix)

CodePudding user response:

First of all, post your code in the question next time. It makes it a lot easier to reply since I could just copy your code and make some changes instead of rewriting it from a screenshot.

Now about what you do wrong: Your for loops don't loop through all matrix values like you think they do. Try something like:

for i in range(len(pixel_matrix)):
    for j in range(len(pixel_matrix[i])):
        if pixel_matrix[i][j] > 0:
            pixel_matrix[i][j] = 1
  • Related