Monday 3 February 2020

python - Channel swap when reading created image with Gdal


I use a function on python (3.5) to create GTIFF with GDAL:


def array2raster2(fname,   matriz, geot, proj):
drv = gdal.GetDriverByName("GTiff")

dst_ds = drv.Create(fname, matriz.shape[1], matriz.shape[0], 3, gdal.GDT_UInt16)
dst_ds.SetGeoTransform(geot)
dst_ds.SetProjection(proj)
dst_ds.GetRasterBand(1).WriteArray(matriz[:, :, 0]) # write r-band to the raster
dst_ds.GetRasterBand(2).WriteArray(matriz[:, :, 1]) # write g-band to the raster
dst_ds.GetRasterBand(3).WriteArray(matriz[:, :, 2])# write g-band to the raster
dst_ds.FlushCache()
dst_ds=None

and works fine, but when I open again the image with gdal.Open() and gdal.ReadAsArray() and check the shape, instead of i.e. (100, 101, 3), it shows (3, 100, 101), can anyone tell me why?



Also when I open the GTIFF on ENVI the orders of band is BGR, when I am saving the image on RGB.



Answer



Try to set colour interpretation of your bands:


dst_ds.GetRasterBand(1).SetRasterColorInterpretation(gdal.GCI_RedBand)
dst_ds.GetRasterBand(2).SetRasterColorInterpretation(gdal.GCI_GreenBand)
dst_ds.GetRasterBand(3).SetRasterColorInterpretation(gdal.GCI_BlueBand)

Also you can try to reverse the order of channels while filling pixels values.


dst_ds.GetRasterBand(3).WriteArray(matriz[:, :, 0])  # write r-band to the    raster
dst_ds.GetRasterBand(2).WriteArray(matriz[:, :, 1]) # write g-band to the raster

dst_ds.GetRasterBand(1).WriteArray(matriz[:, :, 2])# write g-band to the raster

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...