Thursday, 5 April 2018

gdal - How to convert 4-channel PNG files to grayscale geoTIFFs?


I suspect that there exists a gdal tool (gdal_translate?) that will convert a 4-channel PNG (+ world file) to a 1-channel (gray-scale) geoTIFF. From the gdal_translate man page, it appears simple to go in the other direction, i.e. to expand a monochrome raster to a 3 or 4-channel image, but I can't figure out how to go from many channels to one.


If not gdal (hardly conceivable), then another *nix command-line tool?



Answer




You have a few options here.



  • The first is to decide whether you actually need a grey-scale image or whether you want a single band image. If you want the latter then use the GDAL tool rgb2pct.py.

  • Secondly, if your data are all in one particular band already and you just want to shed the remaining bands then you can use GDAL_Translate and specify the band you want in the output.


  • Third, If you are wanting to pack an RGBA image down to grey-scale then you need to calculate the equivalent combined value of the the three bands and output that as one band. It is usual to weight the bands differently as follows: r=0.2989, g=0.5870, b=0.1140. You can do this in GDAl but it is a lot easier to use QGIS' raster calculator and enter the following:


    (myRaster@1 * 0.2989) + (myRaster@2 * 0.5870) + (myRaster@3 * 0.1140)

    However, it is also often recommended to first convert to IHS and then flatten the bands. I think Grass can do this but I've never tried.




  • Alternatively, if you only have one or two images and they have world files as you say, there is another very simple solution that involves no maths and gives a consistent result. This is to use Photoshop, GIMP or some other image processing package to convert to grey-scale for you (and it will probably make a better job of handling partial transparency). Open you image in GIMP (say) and go Image->Mode->Grayscale. Save your output as another file (to preserve the original data) and the make a copy of the world file, renaming it to match your new image's name. I have GIMP already installed and I regularly make grey-scale images this way in preference to using GDAL or QGIS just because it is so easy. The downside of this approach is that not all images are amenable to this treatment as many GeoTiffs etc have a pixel-depth greater than most standard image processing packages understand - so obviously it only works under certain circumstances - though, if you are hacking a colour image down to a grey-scale, you might as well make it 8-bit to begin with and then this method will work.





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...