Python – Copy Coordinates from One .tif File to Another Without Coordinates

coordinatesgeoreferencinggeotiff-tiffopencvpython

So I have done some RGB-channel extraction from a .tif file, meaning I took UAV_image.tif and I have extracted R,G,B channels on three different .tif files. Next, I did some calculations such as result = ((red^2)+(blue^2))/(blue). For all the previous operations I used mainly cv2.imwrite and tiff.imread commands. The problem is that the resulted .tif does not contains coordinates.. How can I copy the coordinates from the initial UAV_image.tif to result.tif? I tried to followed this tutorial:

Use gdalsrsinfo to get the srs of the tiff that still has the
projection:

gdalsrsinfo -o wkt tiffwithsrs.tiff Then copy the output and use
gdal_translate to apply it to a new tiff:

gdal_translate -a_srs '…' tiffwithoutsrs.tif newfixedtif.tif just
paste your projection after the -a_srs option

(source: Using GDAL command line to copy projections)

But the result was to copy both coordinates and colors…!!! Did I do something wrong?

Also, this guy here: "Copy" Image coordinates to another image that is nd.array has a an approach that does not fit my problem, because I do not do any kind of Machine Learning training (as I see to his example – correct me If I am wrong) and I do not use nd.array.

So, the question is how do I copy coordinates from a .tif image that has coordinates to a .tif image that does not have coordinates?

Best Answer

You could do something like this in python using rasterio.

UAV_image = rasterio.open('UAV_image.tif')
new_tif = rasterio.open('new.tif','w',
                        driver='Gtiff',
                        height = UAV_image.height,
                        width = UAV_image.width, 
                        count = 1,
                        crs = UAV_image.crs,
                        transform = UAV_image.transform, 
                        dtype = UAV_image.dtypes)

new_tif.write(result, 1) #result from calculations
UAV_image.close()
new_tif.close()

This should take the geo-information from the original tif and write it to the new one.