Sunday 1 September 2019

python - Why does a TIF file lose projection information when a pixel value is changed?


I am trying to change the pixel value of a tif file (containing projection information) but after the pixel value is changed it is losing projection information.


I am using the Python imaging library for this and the code is like this


import Image
im = Image.open("some tif file")
im.putpixel((2,3),0)

So please help me in solving this ..



Answer



You need a Python library that supports the GeoTIFF format. Libraries that support only the TIFF file discard the projection and geotransform metadata when they are saved. GDAL is the most used open source Python library for reading/writing spatially aware rasters. So, for your example:



from osgeo import gdal

# Load file, and access the band and get a NumPy array
src = gdal.Open('myfile.tif', gdal.GA_Update)
band = src.GetRasterBand(1)
ar = band.ReadAsArray()

# Assign a new raster pixel value
ar[2,3] = 0


# Save/close the file
band.WriteArray(ar)
del ar, band, src

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...