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?

asked Apr 18, 2016 at 12:31
2
  • Do you mean 8-bit paletted? You could use gdal's rgb2pct.py. Commented Apr 18, 2016 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. Commented Apr 18, 2016 at 14:36

1 Answer 1

-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
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
answered Nov 8, 2017 at 14:59
1
  • This creates a 16-bit output Commented Mar 24, 2018 at 15:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.