[GIS] Writing 3 channels to 8-bit TIF in Python using gdal

gdalpython

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?

Best Answer

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
Related Question