Creating a geoTIFF from an image in Matlab

2.2k views Asked by At

I'm trying to create a geoTIFF file in Matlab from the attached png. example image I'm following the example provided in: https://uk.mathworks.com/help/map/examples/exporting-images-and-raster-grids-to-geotiff.html

but need to create georeferencing information from scratch, so using makerefmat and worldfilewrite to acheive this. The code below does not cause a crash, but generates a TIFF that image readers seem to struggle with, so I assume I'm doing something wrong. There may also be some redundancy as I haven't worked with TIFF tags before. Any help appreciated!

% Load image without georeferencing
RGB = imread('uk_dT.png');

% Create worldfile for image.  At present this is done by first creating a
% reference matrix, then using these values to generate a worldfile.
% Longitude spans -17:10 (west to east), latitude 63:47 (north to south)
lonmin = -17; lonmax = 10; latmin = 47; latmax = 63;
DX = (lonmax-lonmin)/(length(RGB(1,:,1))); DY = (latmin-latmax)/(length(RGB(:,1,1)));
R = makerefmat(lonmin, latmax, DX, DY);
worldfilewrite(R,'uk_dT.tfw');

% Read worldfile, create geotiff
REF = worldfileread('uk_dT.tfw','geographic',size(RGB));
geotiffwrite('uk_dT.tif',RGB,REF)
1

There are 1 answers

0
samj On

Out of interest, this code was improved for me on another forum. The result still doesn't open in some image viewers, but I think that's to do with the class of the data. As I'm writing for GIS software this solution works for me.

file = 'uk_dT.png' ; 
[path,name,ext] = fileparts(file) ;

I = imread(file) ;
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)