0

I was using PIL to convert some images from RGB to gray scale in Python, but this code does not work well for GeoTIFF files. It seems that PIL does not seem to work with with GeoTIFF files in particular.

I was using the code:

from PIL import Image

t = Image.open('testfile.tif')
gray_image = image.convert('L')

So I was wondering if there is a way to load an image in say rasterio and then convert it to a gray scale array. Now I could manually do this by writing a simple function to matrix multiply the image array, BUT the files are pretty large and so I run into memory issues. So I would likely need to do a windowed read on the file.

If there is a convenience function in rasterio or GDAL for this, could someone point it out. I searched but could not find anything. Otherwise I can try to work on creating a windowed read.

5
  • I found with duckduckgo.com/?q=rasterio+windowed+read&ia=web this "Windowed reading and writing" document rasterio.readthedocs.io/en/latest/topics/windowed-rw.html as the first hit.
    – user30184
    Commented Oct 5, 2020 at 20:42
  • @user30184 Thanks. Yes, I am aware of the windowed reads functionality. The PIL utility seems to handle converting to grayscale without blowing up the memory, so I imagine it already implements a windowed read, though I am not sure. I was just wondering if rasterio or GDAL provide a similar functionality. I can write windows myself, but was wondering whether I needed to or not.
    – krishnab
    Commented Oct 5, 2020 at 20:47
  • I don't think rasterio has a convenience function to do windowed RW transparently, but implementing block_windows() should only take an extra a line or two of code
    – mikewatt
    Commented Oct 5, 2020 at 21:58
  • @mikewatt yep, that is what I was working on. The additional pain point I discovered is that I also have to apply blocks_windows() over the output array for the gray scale image, haha. I found that trying to preallocate a (31833, 39197) float64 array did not go very well.
    – krishnab
    Commented Oct 5, 2020 at 22:03
  • You can use the same window that the source image's blocks_windows() returns when you go to write the output image, no need to pre-create the output or iterate over anything separately
    – mikewatt
    Commented Oct 5, 2020 at 22:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.