GDAL GeoTIFF – Create Alpha Band for Transparent Specific Color

gdalgeotiff-tiffraster-calculatortransparency

I have a simple RGB GeoTIFF with a white background and want to add a 4th band, the alpha, so that if R+G+B=255*3, then ALPHA=0 ; i.e. if all three bands have a value of 255, then make the fourth zero (or some other number).

This question has been asked before on stackexchange but all the answers provided are not working for me.

So far I have tried:

gdalbuildvrt -srcnodata "255 255 255" -addalpha outfile.vrt infile.tif
gdal_translate outfile.vrt outfile-alpha.tif

but this seems to be an OR statement, where if one band is 255, then it is nodata for the whole pixel so a lot of other colors are wiped out as well.

I tried:

gdal_calc.py -A in.tif --A_band=1 -B in.tif --B_band=2 -C in.tif --C_band=3 ^
 --outfile=alpha.tif --calc="255*((A+B+C)<(765))" --overwrite

And this resulted in a single-band raster with 255 in every cell.

I tried the same with --calc="A+B+C" just to see and the all the white cells added up to 253, rather than 765. Is it some kind of modulus thing? No idea…

I have managed to add alpha bands to a white background using QGIS' Raster Calculator using ORs: ((Band@1 <255) OR (Band@2 <255) OR (Band@3 <255))*255 , but I want to be able to do it through GDAL, so that I can do batch processing.

Best Answer

With some help from Jon, here is an answer:

set pathin=D:\procbox\In
set pathout=D:\procbox\Out


FOR %%N in (%pathin%\*.tif) DO (^
gdal_calc.py -A %%N --A_band=1  --outfile=A.tif --calc="A" --overwrite --type="UInt16" & ^
gdal_calc.py -A %%N --A_band=2  --outfile=B.tif --calc="A" --overwrite --type="UInt16" & ^
gdal_calc.py -A %%N --A_band=3  --outfile=C.tif --calc="A" --overwrite --type="UInt16" & ^
gdal_calc.py -A A.tif --A_band=1 -B B.tif --B_band=1 -C C.tif --C_band=1 ^
--outfile=%pathout%\%%~nN-cov.tif --calc="255*((A+B+C)==765)" --overwrite --type="UInt16")

FOR %%N in (%pathout%\*-cov.tif) DO gdal_polygonize.py %%N -f "ESRI Shapefile" -mask %%N %pathout%\%%~nN.shp

What this script does is it sequentially processes all .tif files in a directory, breaks them down into individual RGB bands (A,B,C .tif) and then calculates a new raster with 255 whenever all these three rasters add up to white (765). What was important was that I was working with a UInt8 tiff, and the input tiffs need to be at least UInt16 for the calculation not to loop over 255.

Then it creates a shapefile around all the white areas. I use this to check survey coverage. If you use the script, please note that in Windows BAT files you break rows with the ^ symbol, rather than with a backslash escape (\) like with shell scripting in Linux.

Related Question