Unboundlocalerror: local variable 'res' referenced before assignment - raster image scanning error (like numpy array)

Asked

Viewed 66 times

1

I created a program that takes raster images (created in arcmap) and recognizes their polygons (their divisions). First, what I did was turn the image into a numpy array. Follow an example image built in matplotlib:

Imagem_exemplo

Then, I associated a Dict in the format:

polygon_dict = {poligon_number : {'class' : 1, 'pix_list' : [(0, 1), (0, 2), (0, 3)...]}}

(note: polygon_number is a whole and class is not relevant here to the problem, but is represented by the color of each polygon in the image)

My question has to do with the following function that I created, BelongsToPolygon, receiving a pair of coordinates x, y (row, column) and returns the number of the polygon to which this coordinate pair belongs.

def BelongsToPolygon(x, y):
    d = polygon_dict           # polygon_dict é uma variável global e com formato referido acima
    for key, val in d.items():
        for i,j in val['pix_list']:
            if i == x and j == y:
                res = key
                break  
    return res

However, I did a test for all matrix coordinates, size 250 x 254:

for i in range(n_rows):
    for j in range(n_cols):
        print('\n')
        print('i, j', i, j, BelongsToPolygon(i, j))

And the output was:

i, j 0 0 0


i, j 0 1 0

...

i, j 32 95 4


i, j 32 96 4


Traceback (most recent call last):

  File "<ipython-input-14-bf48386ad0ff>", line 4, in <module>
    print('i, j', i, j, BelongsToPolygon(i, j))

  File "C:\Users\Sarocas\Desktop\tosendtome\qgis_polygon_no_coords.py", line 519, in BelongsToPolygon
    return res

UnboundLocalError: local variable 'res' referenced before assignment

Can anyone tell me why this error appears? The code is much bigger than this, but it only complains about this function.

1 answer

0


This error appears when trying to use a variable that has not yet been set.

Looking at the code of your function, you can see that the "res" is assigned within a condition (if) - and its value is used only in the command return. It means that this mistake happens in situations where that if is never true, and the execution of the function comes to an end without a value in res (in the case, the requested position was not found).

To avoid an error in such a case, you have to agree a return value for when the position is not found (for example, None), and assign this value to the variable before entering the links for. In that case if the search never find anything, when arriving at the return, res will have this default value:

def BelongsToPolygon(x, y):
    d = polygon_dict           # polygon_dict é uma variável global e com formato referido acima
    res = None
    for key, val in d.items():
        for i,j in val['pix_list']:
            if i == x and j == y:
                res = key
                break  
    return res
  • Thank you very much, it works! Such an obvious mistake...

  • Welcome to stackoverflow in English!

Browser other questions tagged

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