4

With one 2-d array in the shape of (100, 100), I want to save it into raster file in .tiff format.

I can use gdal package to read tiff files which are already exist. But I still can't find a simple way to transform the 2-d array into tiff file.

Using plt.imsave("xx.tif",array) or

def array_to_raster(array):
    """Array > Raster
    Save a raster from a C order array.
    :param array: ndarray
     """
    dst_filename = 'xxx.tiff'
    x_pixels = 100  # number of pixels in x
    y_pixels = 100  # number of pixels in y
    driver = gdal.GetDriverByName('GTiff')
    dataset = driver.Create(
           dst_filename,
           x_pixels,
           y_pixels,
           1,
           gdal.GDT_Float32, )
    dataset.GetRasterBand(1).WriteArray(array)
    dataset.FlushCache()  # Write to disk.
    return dataset, dataset.GetRasterBand(1)  

They all failed to achieve my target. The second method was adapted from here which can transform an array into a geotiff with a projection.

Is there some simple way to save array into .tiff, so I can call it by import the tiff file next time.

Any advices would be appreciate.

2 Answers 2

8

A tif raster could be considered as 'array+proj+geotransforms'. If you want to write an array to a tiff ,you can refer to the following code:

dst_filename = 'xxx.tiff'
x_pixels = 100  # number of pixels in x
y_pixels = 100  # number of pixels in y
driver = gdal.GetDriverByName('GTiff')
dataset = driver.Create(dst_filename,x_pixels, y_pixels, 1,gdal.GDT_Float32)
dataset.GetRasterBand(1).WriteArray(array)

# follow code is adding GeoTranform and Projection
geotrans=data0.GetGeoTransform()  #get GeoTranform from existed 'data0'
proj=data0.GetProjection() #you can get from a exsited tif or import 
dataset.SetGeoTransform(geotrans)
dataset.SetProjection(proj)
dataset.FlushCache()
dataset=None
Sign up to request clarification or add additional context in comments.

2 Comments

For the record, the last 4 lines should read: dataset.SetGeoTransform(geotrans) dataset.SetProjection(proj) dataset.FlushCache() dataset=None
What is outds ?
2

Easiest way with imageio

If you don't care about its projection it's a oneliner:

import imageio
imageio.imwrite('test.tiff', [[0,255],[255,0]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.