0

I have a GTiff raster with values from 0 to 255 and I want to reclassify 2 values ( 1 and 2) to 1, and the rest set them to NaN, in order to polygonize later and obtain polygons only for the desired value.

Is there a way of doing this?

driver = gdal.GetDriverByName( 'GTiff')
file = gdal.Open( 'area.tif')
band = file.GetRasterBand(1)
lista = band.ReadAsArray()
lista[np.where(lista == 2)] = 1
lista[np.where(lista != 1)] = np.NaN

This fails due to ValueError: cannot convert float NaN to integer

2

Try masking your array as follows:

lista = np.where(lista == 1, 1, lista)
lista = np.where(lista != 1, np.NaN, lista)

The structure of this function is np.where(condition, x, y) where the function yields x if the condition is True or y if it is False.

1

If you read an array from a raster using band.ReadAsArray, it appears that the array type is numpy.uint8 (check yours with lista.dtype), and as such can only accept integer values. Have a look here.

As such, you have three options:

1) Convert your array to a float array: listaFloat = lista.astype(float)

2) Replace unwanted values with invalid integers: lista[np.where(lista != 1)] = -99999

3) Mask your values using: lista[np.where(lista != 1)] = np.ma.masked

You would have to see what works best when going forward and creating a raster from the numpy array; that depends on the format you'll be using. I assume that the first or second options should solve your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.