-1

How can I do processing with .tif images in Python?

For example suppose I have "Red_channel.tif" and "Blue_channel.tif" and I want to do the calculation (and produce a new .tif) like this:

"output.tif" = ("Red_channel.tif" + (("Blue_channel.tif")^3) + 4 + sqrt("Red_channel.tif"))
3
  • 1
    What GIS software are you using? What have you tried?
    – PolyGeo
    Commented Aug 8, 2021 at 21:42
  • I am asking about python code....
    – Steven
    Commented Aug 8, 2021 at 21:50
  • We're a little different from other sites. We're a Q&A site, not a discussion forum. For questions that involve code we ask that you show us where you are stuck with your own code by including a code snippet in your question. Please check out our short tour for more about how the site works. This question now has a matplotlib/rasterio answer so if it's another Python library that you wish to ask about then please do that in a new question.
    – PolyGeo
    Commented Aug 8, 2021 at 22:52

1 Answer 1

3

If georeferencing is not important to you, you can simply do it with matplotlib.

import matplotlib.pyplot as plt

red = plt.imread('path/to/Red_channel.tif')
blue = plt.imread('path/to/Blue_channel.tif')

result = red + blue**3 + 4 + red**0.5

plt.imsave('path/to/Output.tif', result)

If you want to maintain the georeferencing you should use rasterio instead.

import rasterio
with rasterio.open('path/to/Red_channel.tif') as f:
    red = f.read()
    profile = f.profile

with rasterio.open('path/to/Blue_channel.tif') as f:
    blue = f.read()

result = red + blue**3 + 4 + red**0.5

with rasterio.open('path/to/Output.tif', 'w', **profile) as dst:
    dst.write(result)
1
  • Parsa you are amazing!!!
    – Steven
    Commented Aug 9, 2021 at 10:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.