[GIS] How to save raster with projection into Python

gdalopencvpythonraster

I applied a raster processing that is already in a known coordinate system with this code,

import cv2
import numpy as np
from matplotlib import pyplot as src

img = cv2.imread(r'E:\2_PROJETS_DISK_E\threshold\621.tif',0)

# Otsu's thresholding after Gaussian filtering
blur = cv2.GaussianBlur(img,(5,5),0)
ret1,th1 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

for i in xrange(1):
 plt.imshow(images[i*3+2],'gray')
 plt.xticks([]), plt.yticks([])
plt.show()

cv2.imwrite( r'E:\2_PROJETS_DISK_E\threshold\621-1.tif',th1);

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

How can I keep the same coordinate system of the initial raster (without tranforming the output raster into local coordinates)

Since I am new to Python, and I have no knowledge of Python, i would like someone to correct me my script please.

Best Answer

You should be able to set the projection and the geotransform of your new raster using the information of the previous raster.

Can you test the following code? (You can append it to your code or create a new script a run it after the code you provided).

import gdal

# open original raster and get projection and geotransform
original_ds = gdal.Open(r'E:\2_PROJETS_DISK_E\threshold\621.tif', 0)
sr = ds.GetProjection()
gt = ds.GetGeoTransform()
del original_ds

# open target raster (in editing mode) and set the projection and geotransform
ds = gdal.Open(r'E:\2_PROJETS_DISK_E\threshold\621-1.tif', 1)
ds.SetProjection(sr)
ds.SetGeoTransform(gt)

# save and close target raster
del ds