1

I tried to make an algorithm in Python where I entered a georeferenced raster (EPSG 32722 projection system), all its NaN values ​​were transformed to zero, and then a new image was saved with the EPSG 4326 projection system.

import skimage.io
import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer

pathhr = 'C:\\Users\\dataset\\S30W051.tif'
HR = skimage.io.imread(pathhr)
df1 = pd.DataFrame(HR)
imputer = SimpleImputer(fill_value=np.nan, strategy='mean')
X = imputer.fit_transform(df1)
X = pd.DataFrame(X, columns=df1.columns)
X.isna().sum()

#save function
savedata = df1.to_numpy()
skimage.io.imsave('C:\\Users\\dataset\\S30W051_TEST.tif', savedata)

But when I save my raster at the end of this script, I get a non-georeferenced TIFF raster.

How do I save this new raster with the EPSG 4326 projection system?

1
  • 3
    Use a geospatial library as rasterio instead of skimage
    – gene
    Jun 5 '21 at 15:25
1

It's easy using a library that's designed to handle georeferenced raster data like GDAL or rasterio (based on GDAL).

Here is an example based on the docs for reprojecting with rasterio:

import numpy as np
import rasterio as rio
from rasterio.warp import calculate_default_transform, reproject, Resampling
from sklearn.impute import SimpleImputer


pathhr = 'C:\\Users\\dataset\\S30W051.tif'
pathout = 'C:\\Users\\dataset\\S30W051_TEST.tif'

dst_crs = 'EPSG:4326'
imputer = SimpleImputer(fill_value=np.nan, strategy='mean')

with rio.open(pathhr) as src:
    profile = src.profile.copy()
    transform, width, height = calculate_default_transform(
        src.crs, dst_crs, src.width, src.height, *src.bounds)
    profile.update({
        'crs': dst_crs,
        'transform': transform,
        'width': width,
        'height': height
    })

    with rio.open(pathout, 'w', **profile) as dst:
        for i in range(1, src.count + 1):

            data = np.nan_to_num(src.read(i))
            #Or
            data = imputer.fit_transform(data)  # use array not pandas df 

            reproject(
                source=rio.band(src, i),
                destination=rio.band(dst, i),
                src_transform=src.transform,
                src_crs=src.crs,
                dst_transform=transform,
                dst_crs=dst_crs,
                resampling=Resampling.nearest
            )
0

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.