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'
Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
asked Nov 23, 2020 at 23:05

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

answered Nov 24, 2020 at 1:47
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!")
answered Dec 25, 2020 at 16:20
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.

answered Nov 19, 2022 at 6:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.