0

I am trying to create multiple multi-band images based off of Landsat data in Python. I am using PIL for this. How do I use PIL to create multiple multi-band images at the same time?

Here is the code:

import glob
from PIL import Image

year = 1999
band5_list = glob.glob('LE07_L1TP_037032_*_01_T1_B5.TIF')
band4_list = glob.glob('LE07_L1TP_037032_*_01_T1_B4.TIF')
band3_list = glob.glob('LE07_L1TP_037032_*_01_T1_B3.TIF')

for band5 in band5_list:
    for band4 in band4_list:
        for band3 in band3_list: 
            Band_5 = Image.open(band5).convert('L')
            Band_4 = Image.open(band4).convert('L')
            Band_3 = Image.open(band3).convert('L')
            try:
                Veg_Image = Image.merge('RGB', (Band_5, Band_4, Band_3))
            except ValueError:
                print('Impossible to merge. Try again.')
                break
            year += 1
            Veg_Image.save('Landsat_' + str(year) + '.tif')
  • 1
    Please also avoid try: except: clauses in code you post (you can use them in your own code obviously) so that any errors don't get hidden. Then can you edit your question and add more details about any errors (complete traceback formatted as code using the {} button) or unexpected outputs. Thanks! – user2856 Sep 15 '18 at 23:20
  • 1
    Can I also suggest you consider using rasterio instead of PIL. rasterio is designed for georeferenced raster imagery, unlike PIL. – user2856 Sep 15 '18 at 23:26
1

Your nested loops will cause issues, as for each element in Band5_list you will loop through all elements in Band4_list and for each element in Band4_list you'll loop through all elements in Band3_list.

So assuming you have 3 lists with 5 bands each, Band5_list gets looped through once, Band4_list five times and Band3_list 25 times.

Instead, try using the zip() function:

for band5, band4, band3 in zip(Band5_list, Band4_list, Band3_list):
    Band_5 = Image.open(band5).convert('L')
    Band_4 = Image.open(band4).convert('L')
    Band_3 = Image.open(band3).convert('L')
    etc...
| improve this answer | |
  • Thanks. By the way, does the order of the bands in Image.merge matter? – Nathan Fleischman Sep 16 '18 at 1:48
  • By the way, can you also tell me how to do it in rasterio? I know that you mentioned that that works with georeferenced imagery. – Nathan Fleischman Sep 17 '18 at 21:06
  • 1
    Start by looking at the documentation rasterio.readthedocs.io/en/latest/search.html?q=Merge There's a command line tool and a python API. – user2856 Sep 17 '18 at 21:20
  • I have. I am using the Python API, not the command line tool. – Nathan Fleischman Sep 17 '18 at 23:36
  • 1
    Then ask a new question – user2856 Sep 17 '18 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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