MATLAB: Adding an alpha channel to geoTIFF image

alphageotiffgeotiffwriteimageMapping Toolboxtiff

Trying to add an alpha (transparency) channel to the RGB data in a georeferenced tiff image. I was led through the process of creating the geotiff in a separate question. The first part of the code creates a geotiff from the attached png file, the second part creates a mask from white regions, appends it to the RGB data and attempts to modify the appropriate tags before rewriting the geotiff. However the resultant image is blank. I suspect I'm doing something wrong with the 'photometric' tag but can't see the problem.
file = 'uk_dT.png' ;
[path,name,ext] = fileparts(file) ;
I = imread(file) ;
I = flipud(I);
lonmin = -17; lonmax = 10; latmin = 47; latmax = 63;
% Write to geotiff
R = georasterref('RasterSize',size(I),'LatitudeLimits',[latmin,latmax],'LongitudeLimits',[lonmin,lonmax]);
tiffile = strcat(name,'.tif') ;
geotiffwrite(tiffile,I,R) % original code
%%Now we have a geotiff but need transparency.
% Make alpha mask by identifying white regions
S = sum(I,3);
mask = 255*ones(size(I,1),size(I,2));
mask(S==765) = 0; % create mask
I = cat(3,I,mask); % concatenate alpha channel onto RGB data
info = geotiffinfo(tiffile); % reload RGB tiff data
% use Tiff tags to append alpha data
tiffile2 = strcat(name,'2.tif') ;
geotiffwrite(tiffile2,I,R,'GeoKeyDirectoryTag', ...
info.GeoTIFFTags.GeoKeyDirectoryTag,'TiffTags', ...
struct('ExtraSamples',Tiff.ExtraSamples.AssociatedAlpha, ...
'Photometric',Tiff.Photometric.Separated));

Best Answer

You're right that currently in MATLAB, there is no way to add an alpha channel to your geotiff.
But here is a workaround! To do this, you will have to swap out your version of "geotiffwrite" with a new one I have attached.
First, make sure you backup/rename the original version of "geotiffwrite" (under "<matlabroot>/matlab/toolbox/map/mapformats/") so that you can get to the original version if you ever need to. Then replace it with the attached modified version of "geotiffwrite".
With the modified "geotiffwrite", the following code can be used:
geotiffwrite(tiffile2, I, R, ...
'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag, ...
'TiffTags', struct( ...
'ExtraSamples',Tiff.ExtraSamples.AssociatedAlpha, ...
'Photometric',Tiff.Photometric.RGB))
where "I" is your M-by-N-by-4 matrix with alpha data. And the resulted file can then be correctly interpreted by other applications.