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:
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.
Thank you very much, it works! Such an obvious mistake...
– Sara Isabel Aleixo Perestrelo
Welcome to stackoverflow in English!
– jsbueno