0

I have made some processing on some satellite images as numpy arrays. I want to export the data as tif images again to see the result I read ùy image with rasterio

sentinel2 = rasterio.open('sentinel2.tif')

and my processed array is date1seg

According to this >>> new_dataset.write(Z, 1) I used that to export the image but this error appears

sentinel2.write(date1seg, 1)
AttributeError: 'DatasetReader' object has no attribute 'write'

3 Answers 3

1

You should opening your tif file in write mode, by passing the write arg and use the context manager so the file closes once youre finished with it. You can pass in any meta info you need also and then write to the tif, passing in your data and the band you want to write to.

with rasterio.open('sentinel2.tif', 'w', **meta) as dst:
    dst.write(date1seg, 1)

Documentation can be found here - https://rasterio.readthedocs.io/en/latest/quickstart.html#opening-a-dataset-in-writing-mode

1

I've already developed a python function that get /path/to/export/directory, (n x m) numpy array and meta to generate desired .tif file.

import os
import rasterio

def export_to_tiff(directory, matrix, metadata):
    """
    This function get Numpy ndarray and related metadata to create
    a .tif file as the results of process.
    \nInputs=> A directory for exported .tif file, Numpy and meta
    \nOutputs=> A path to result .tif file
    """
    file_name = os.path.split(directory)[1]
    kwargs = metadata
    kwargs.update(dtype=rasterio.float32, count = 1)
    try:
        with rasterio.open(directory, 'w', **kwargs) as dst:
            dst.write_band(1, matrix.astype(rasterio.float32))
            print('\n File was created successfully.\n%s' % file_name)
    except:
        raise Exception("Error in exporting dataset to .tif!")
0

I know that the question is related to rasterio, however, I found out that writing .tif files with tifffile is way easier. You only need to do:

tifffile.imsave(path, numpy_array_image)

where numpy_array_image is the numpy matrix image and path is the full path where you want to save the file.

Your Answer

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

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