2

I have some Python code to write 3 channels to file. Here, channels is an array of 3 numpy 2D-arrays (RGB), outfile is the filename, and rows and cols are the image dimensions.

def save_tiff(channels, outfile, rows, cols):
    outdriver = gdal.GetDriverByName("GTiff")
    outdata = outdriver.Create(str(outfile)+".tif", rows, cols, len(channels), gdal.GDT_Byte)

    # write the arrays to the file
    i = 1
    for c in channels:
        outdata.GetRasterBand(i).WriteArray(c)
        outdata.GetRasterBand(i).FlushCache() 
        i += 1

However, this results in 24-bit output images (probably because of 3xGDT_Byte channel). How do I get a single 8-bit image from 3 channels (R,G,B) in Python using gdal?

  • Do you mean 8-bit paletted? You could use gdal's rgb2pct.py. – Steven Kay Apr 18 '16 at 14:32
  • I'm unsure what paletted means, in the end I want to re-attach geodata to my TIF file using listgeo/geotifcp but it doesn't seem to work with 24-bit images. I tested it succesfully with an example 8-bit image so that's why I'm trying to convert it. – appel Apr 18 '16 at 14:36
-1

I always use this function to create 3 channel images (or more, just changing the parameters):

def array2raster2(fname,   matriz, geot, proj): #filename, image, geoTransformation, Projection
    drv = gdal.GetDriverByName("GTiff")
    dst_ds = drv.Create(fname, matriz.shape[1], matriz.shape[0], 3,  gdal.GDT_UInt16) #Change the 3 by the number of channels you want and gdal.GDT_Uint16 can be changed to type of data you want
    dst_ds.SetGeoTransform(geot)
    dst_ds.SetProjection(proj)
    dst_ds.GetRasterBand(1).WriteArray(matriz[:, :, 0])  
    dst_ds.GetRasterBand(2).WriteArray(matriz[:, :, 1])  
    dst_ds.GetRasterBand(3).WriteArray(matriz[:, :, 2])
    dst_ds.FlushCache()
    dst_ds=None
  • This creates a 16-bit output – Marcelo Villa Mar 24 '18 at 15:15

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.