This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

geotiffwrite

Write GeoTIFF file

Syntax

geotiffwrite(filename,A,R)
geotiffwrite(filename,X,cmap,R)
geotiffwrite(___,Name,Value)

Description

example

geotiffwrite(filename,A,R) writes a georeferenced image or data grid, A, spatially referenced by R, into an output file, filename.

geotiffwrite(filename,X,cmap,R) writes the indexed image in X and its associated colormap, cmap, to filename. X is spatially referenced by R.

example

geotiffwrite(___,Name,Value) writes an image or data grid with one or more Name,Value pair arguments that control various characteristics of the output file.

Examples

collapse all

Read JPEG image from file.

basename = 'boston_ovr';
imagefile = [basename '.jpg'];
RGB = imread(imagefile);

Derive world file name from image file name, read the world file, and construct a spatial referencing object.

worldfile = getworldfilename(imagefile);
R = worldfileread(worldfile, 'geographic', size(RGB));

Write image data and referencing data to GeoTIFF file.

filename = [basename '.tif'];
geotiffwrite(filename, RGB, R)

Construct an empty map axes and display the map.

figure
usamap(RGB, R)
geoshow(filename)

Read data from a file in classic TIFF format into the workspace.

infilename = 'boston.tif';
[A,R] = geotiffread(infilename);

Retrieve the metadata from the file. You pass this into the new BigTIFF version of the file.

info = geotiffinfo(infilename);

Extract the value of the GeoKeyDirectoryTag field from the info structure returned by geotiffinfo. Set the value of two TIFF tags that specify the length and width of tiles.

geoTags = info.GeoTIFFTags.GeoKeyDirectoryTag;
tiffTags = struct('TileLength',1024,'TileWidth',1024);

Write the data to a new GeoTIFF file, using the TiffType parameter to specify the file format as 'bigtiff'. Include the geoTags information and the tiffTags in the metadata in the new file.

outfilename = 'boston_bigtiff.tif';
geotiffwrite(outfilename,A,R,'GeoKeyDirectoryTag',geoTags, ...
      'TiffType','bigtiff','TiffTags',tiffTags) 

Read data from WMS server.

nasaLayers = wmsfind('nasa', 'SearchField', 'serverurl');
layerName = 'bluemarbleng';
layer = refine(nasaLayers, layerName,  'SearchField', 'layername', ...
  'MatchType', 'exact');
[A, R] = wmsread(layer(1));

Write data to GeoTIFF file.

filename = [layerName '.tif'];
geotiffwrite(filename, A, R)

View data in file.

figure
worldmap world
geoshow(filename)

Read the two adjacent orthophotos and combine them.

X_west = imread('concord_ortho_w.tif');
X_east = imread('concord_ortho_e.tif');
X = [X_west X_east];

Construct referencing objects for the orthophotos and for their combination.

R_west = worldfileread('concord_ortho_w.tfw', 'planar', size(X_west));
R_east = worldfileread('concord_ortho_e.tfw', 'planar', size(X_east));
R = R_west;
R.XLimWorld = [R_west.XLimWorld(1) R_east.XLimWorld(2)];
R.RasterSize = size(X);

Write the combined image to a GeoTIFF file. Use the code number, 26986, indicating the PCS_NAD83_Massachusetts Projected Coordinate System.

coordRefSysCode = 26986;
filename = 'concord_ortho.tif';
geotiffwrite(filename, X, R, 'CoordRefSysCode', coordRefSysCode);

Display the map.

figure
mapshow(filename)

Read GeoTIFF file.

[A, R] = geotiffread('boston.tif');

Specify subset of data that you want to write.

m = size(A,1);
n = 1024;
firstrow = m-n+1;
lastrow = m;
firstcol = 1;
lastcol = n;
subImage = A(firstrow:lastrow, firstcol:lastcol, :);
xi = [firstcol - .5, lastcol + .5];
yi = [firstrow - .5, lastrow + .5];
[xlimits, ylimits] = intrinsicToWorld(R, xi, yi);
subR = R;
subR.RasterSize = size(subImage);
subR.XLimWorld = sort(xlimits);
subR.YLimWorld = sort(ylimits);
info = geotiffinfo('boston.tif');

Write subset to file.

filename = 'boston_subimage.tif';
geotiffwrite(filename, subImage, subR,  ...
       'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag);
figure
mapshow(filename);

This example shows how to write the Mount Washington SDTS DEM terrain data to GeoTIFF. The data are referenced to Universal Transverse Mercator (UTM), Zone 19, in the North American Datum of 1927. This corresponds to the GeoTIFF PCS_NAD27_UTM_zone_19N code number 26719. Set the raster interpretation to 'postings' because the data is USGS DEM. This corresponds to the GeoTIFF raster type PixelIsPoint.

Read SDTS DEM data.

[Z, refmat] = sdtsdemread('9129CATD.ddf');
R = refmatToMapRasterReference(refmat, size(Z), 'postings');
key.GTModelTypeGeoKey  = 1;  % Projected Coordinate System (PCS)
key.GTRasterTypeGeoKey = 2;  % PixelIsPoint
key.ProjectedCSTypeGeoKey = 26719;
filename = '9129.tif';
geotiffwrite(filename, Z, R, 'GeoKeyDirectoryTag', key);

Plot the outline of the state of New Hampshire in UTM.

S = shaperead('usastatelo', 'UseGeoCoords', true, 'Selector',...
    {@(name) any(strcmp(name,{'New Hampshire'})), 'Name'});
proj = geotiffinfo(filename);
[x, y] = projfwd(proj, [S.Lat], [S.Lon]);
figure
mapshow(x,y)

Display the GeoTIFF DEM file.

hold on
h = mapshow(filename, 'DisplayType', 'surface');
demcmap(get(h,'ZData'))

This example shows how to read a file containing RPC metadata, modify the file, and then write the file, including the RPC metadata in the new file. To illustrate this process, the example first creates a sample TIFF file containing RPC Metadata.

Create a Sample TIFF File with RPC Metadata

Create a sample test TIFF file containing RPC metadata. For this test file, create a toy image and a referencing object associated with the image.

myimage = zeros(180,360);
latlim = [-90 90];
lonlim = [-180 180];
R = georefcells(latlim,lonlim,size(myimage));

Create an RPCCoefficientTag metadata object and set some fields with typical values. The toolbox uses the RPCCoefficientTag object to represent RPC metadata in human readable form.

rpctag = map.geotiff.RPCCoefficientTag;
rpctag.LineOffset = 1;
rpctag.SampleOffset = 1;
rpctag.LineScale = 2;
rpctag.SampleScale = 2;
rpctag.GeodeticHeightScale = 500;

Write the image, the associated referencing object, and the RPCCoefficientTag object to a file.

geotiffwrite('myfile',myimage,R,'RPCCoefficientTag',rpctag)

Read the Metadata and Image Data from the Sample TIFF File

Read the metadata and the image data from the test file. geotiffinfo returns the RPC metadata in the GeoTIFFTags field of the structure returned.

info = geotiffinfo('myfile');
[imagedata, R] = geotiffread('myfile');

Write Modified Image Data and RPC Metadata to File

First modify the image data read from the file. For example, set all the zero-valued pixels to 1 in the image.

imagedata(imagedata==0)= 1;

Write the modified image to a file, along with the RPC metadata from the original file.

geotiffwrite('myfile2',imagedata,R,...
    'RPCCoefficientTag',info.GeoTIFFTags.RPCCoefficientTag)

This example shows how to write RPC coefficient metadata to a TIFF file. In a real workflow, you would create the RPC coefficient metadata according to the TIFF extension specification. This example does not show the specifics of how to create valid RPC metadata. To simulate raw RPC metadata, the example creates a sample TIFF file with RPC metadata and then uses imfinfo to read this RPC metadata in raw, unprocessed form from the file. The example then writes this raw RPC metadata to a file using the geotiffwrite function.

Create Raw RPC Coefficient Metadata

To simulate raw RPC metadata, create a simple test file and write some RPC metadata to the file. For this test file, create a toy image and a referencing object associated with the image.

myimage = zeros(180,360);
latlim = [-90 90];
lonlim = [-180 180];
R = georefcells(latlim,lonlim,size(myimage));

Create an RPCCoefficientTag metadata object and set some of the fields. The toolbox uses the RPCCoefficientTag object to represent RPC metadata in human readable form.

rpctag = map.geotiff.RPCCoefficientTag;
rpctag.LineOffset = 1;
rpctag.SampleOffset = 1;
rpctag.LineScale = 2;
rpctag.SampleScale = 2;
rpctag.GeodeticHeightScale = 500;

Write the image, the associated referencing object, and the RPCCoefficientTag object to a file.

geotiffwrite('myfile',myimage,R,'RPCCoefficientTag',rpctag)

Read Raw RPC Coefficient Metadata

Read the RPC coefficient metadata from the test file using the imfinfo function. When it encounters unfamiliar metadata, imfinfo returns the data, unprocessed, in the UnknownTags field. Note how the UnknownTags field contains an array of 92 doubles. This is the raw RPC coefficient metadata, read from the file in unprocessed form.

info = imfinfo('myfile.tif');
info.UnknownTags
ans = struct with fields:
        ID: 50844
    Offset: 10672
     Value: [1x92 double]

Write Raw RPC Metadata to a File

Write the raw RPC metadata to a file. First, extract the RPC coefficient metadata from the info structure.

value = info.UnknownTags.Value;

Then, construct an RPCCoefficientTag object, passing the raw RPC metadata (array of 92 doubles) as an argument.

rpcdata = map.geotiff.RPCCoefficientTag(value)
rpcdata = 
  RPCCoefficientTag with properties:

                BiasErrorInMeters: -1
              RandomErrorInMeters: -1
                       LineOffset: 1
                     SampleOffset: 1
           GeodeticLatitudeOffset: 0
          GeodeticLongitudeOffset: 0
             GeodeticHeightOffset: 0
                        LineScale: 2
                      SampleScale: 2
            GeodeticLatitudeScale: 1
           GeodeticLongitudeScale: 1
              GeodeticHeightScale: 500
        LineNumeratorCoefficients: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
      LineDenominatorCoefficients: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
      SampleNumeratorCoefficients: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
    SampleDenominatorCoefficients: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

Pass the RPCCoefficientTag object to the geotiffwrite function and write the RPC metadata to a file.

geotiffwrite('myfile2',myimage,R,'RPCCoefficientTag',rpcdata)

To verify that the data was written to the file, read the RPC metadata from the TIFF file using geotiffinfo. Compare the returned RPC metadata with the metadata written to the test file.

ginfo = geotiffinfo('myfile2');
ginfo.GeoTIFFTags.RPCCoefficientTag
ans = 
  RPCCoefficientTag with properties:

                BiasErrorInMeters: -1
              RandomErrorInMeters: -1
                       LineOffset: 1
                     SampleOffset: 1
           GeodeticLatitudeOffset: 0
          GeodeticLongitudeOffset: 0
             GeodeticHeightOffset: 0
                        LineScale: 2
                      SampleScale: 2
            GeodeticLatitudeScale: 1
           GeodeticLongitudeScale: 1
              GeodeticHeightScale: 500
        LineNumeratorCoefficients: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
      LineDenominatorCoefficients: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
      SampleNumeratorCoefficients: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
    SampleDenominatorCoefficients: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

Input Arguments

collapse all

Name and location of output file, specified as a string scalar or character vector. If your filename includes an extension, it must be '.tif' or '.TIF'. If the input, A, is at least 160-by-160 in size, the output file is a tiled GeoTIFF file. Otherwise, geotiffwrite organizes the output file as rows-per-strip.

Data Types: char | string

Georeferenced image or data grid, specified as one of the following:

  • An M-by-N numeric matrix representing a grayscale image or data grid

  • An M-by-N-by-P numeric array representing a color image, multispectral image, hyperspectral image, or data grid

The coordinates of A are geographic and in the 'WGS 84' coordinate system, unless you specify 'GeoKeyDirectoryTag' or 'CoordRefSysCode' and indicate a different coordinate system.

Data Types: double | single | uint8 | uint16 | uint32 | uint64 | int8 | int16 | int32 | int64 | logical

Spatial referencing information, specified as a geographic raster reference object of type GeographicCellsReference or GeographicPostingsReference, a map raster reference object of type MapCellsReference or MapPostingsReference, a referencing matrix, or a referencing vector.

If you are working with image coordinates in a projected coordinate system and R is a map raster reference object or a referencing matrix, specify 'GeoKeyDirectoryTag' or 'CoordRefSysCode' accordingly.

Indexed image data, specified as an M-by-N numeric matrix.

Data Types: uint8 | uint16

Color map associated with indexed image X, specified as an c-by-3 numeric matrix. There are c colors in the color map, each represented by a red, green, and blue pixel value.

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: 'CoordRefSysCode',26986

Coordinate reference system code for the coordinates of the data, specified as the comma-separated pair consisting of 'CoordRefSysCode' and a positive integer, string scalar, or character vector. You can specify coordinates in either a geographic or a projected coordinate system. If you specify the coordinate system with a string scalar or character vector, include the 'EPSG:' prefix. See Tips for a link to the GeoTiff Specification or the EPSG data files (pcs.csv and gcs.csv) for the code numbers.

If you specify both the GeoKeyDirectoryTag and the CoordRefSysCode, the coordinate system code in CoordRefSysCode takes precedence over the coordinate system key found in the GeoKeyDirectoryTag. If one value specifies a geographic coordinate system and the other value specifies a projected coordinate system, you receive an error.

If you do not specify a value for this argument, the default value is 4326, indicating that the coordinates are geographic and in the 'WGS 84' geographic coordinate system.

Example: 26986

Example: 'EPSG:26986'

GeoKey directory tag, specified as the comma-separated pair consisting of 'GeoKeyDirectoryTag' and a structure that specifies the GeoTIFF coordinate reference system and meta-information. The structure contains field names that match the GeoKey names in the GeoTIFF specification. The field names are case insensitive. The structure can be obtained from the GeoTIFF information structure, returned by geotiffinfo, in the field, GeoTIFFTags.GeoKeyDirectoryTag.

if you specify the GTRasterTypeGeoKey field, geotiffwrite ignores it. The value for this GeoKey is derived from R. If you set certain fields of the GeoKeyDirectoryTag to inconsistent settings, you receive an error message. For instance, if R is a geographic raster reference object or a refvec, and you specify a ProjectedCSTypeGeoKey field or you set the GTModelTypeGeoKey field to 1 (projected coordinate system), you receive an error. Likewise, if R is a map raster reference object and you do not specify a ProjectedCSTypeGeoKey field or a CoordRefSysCode, or the GTModelTypeGeoKey field is set to 2 (geographic coordinate system), you receive an error message.

Values for the optional RPC TIFF tag, specified as the comma-separated pair consisting of 'RPCCoefficientTag' and an RPCCoefficientTag object.

Values for the TIFF tags in the output file, specified as the comma-separated pair consisting of 'TiffTags' and a structure. The field names of the structure match the TIFF tag names supported by the Tiff class. The field names are case insensitive.

You cannot set most TIFF tags using the structure input.

TiffTags Exceptions

BitsPerSampleSubFileTypeGeoAsciiParamsTag
SampleFormatSubIFDGeoDoubleParamsTag
SamplesPerPixelTileByteCountsGeoKeyDirectoryTag
StripByteCountsTileOffsetsModelPixelScaleTag
StripOffsetsImageLengthModelTiepointTag
ColorMapImageWidthModelTransformationTag

The function sets several TIFF tags. The field names corresponding to the TIFF tag, their corresponding field values set by the function, their permissible values (if different from the Tiff class), and their data type are noted in the following table.

Automatic TIFF Tags

Field NameDescription
Compression

Type of image compression. The default is 'PackBits'. Other permissible values are 'LZW', 'Deflate', and 'none'.

Numeric values, Tiff.Compression.LZW, Tiff.Compression.PackBits, Tiff.Compression.Deflate, or Tiff.Compression.None can also be used.

PhotometricInterpretation

Type of photometric interpretation. The field name can be shortened to Photometric. The value is set based on the input image characteristic, using the following algorithm: If A is [M-by-N-by-3] and is class type uint8 or uint16, then the value is 'RGB'. For all other sizes and data types, the value is 'MinIsBlack'. If the X, CMAP syntax is supplied, the value is 'Palette'. If the value is set to 'RGB' and A is not [M-by-N-by-3], an error is issued. Permissible values are 'MinIsBlack', 'RGB', 'Palette', 'Separated'. The numeric values, Tiff.Photometric.MinIsBlack, Tiff.Photometric.RGB, Tiff.Photometric.Palette, Tiff.Photometric.Separated can also be used.

Software

Software maker of the file. The value is set to the value 'MATLAB, Mapping Toolbox, The MathWorks, Inc.'. To remove the value, set the tag to the empty string or character vector ('').

RowsPerStrip

A scalar positive integer-valued number specifying the desired rows per strip in the output file. If the size of A is less than [160-by-160], geotiffwrite sets RowsPerStrip to 1. If you specify RowsPerStrip and TileWidth, with or without TileLength, geotiffwrite issues an error.

TileWidth

A scalar positive integer-valued number and a multiple of 16 specifying the width of the tiles. TileWidth is set if the size of A is greater than [160-by-160]. If so, the value is such that a maximum of [10-by-10] tiles are created. If you specify both RowsPerStrip and TileWidth, geotiffwrite issues an error.

TileLength

A scalar positive integer-valued number and a multiple of 16 specifying the length of the tiles. TileLength is set if the size of A is greater than [160-by-160]. If so, the value is such that a maximum of [10-by-10] tiles are created. If you specify both RowsPerStrip and TileLength, geotiffwrite issues an error.

Type of TIFF file, specified as the comma-separated pair consisting of 'TiffType' and either 'classictiff' or 'bigtiff'. The 'classictiff' value creates a Classic TIFF file. The 'bigtiff' value creates a BigTIFF file. In BigTIFF format, files can be larger than 4 GB.

While using the 'bigtiff' format enables you to create files larger than 4 GB, the data you want to write must fit in memory.

Tips

  • If you are working with image coordinates in a projected coordinate system and R is a map raster reference object or a referencing matrix, set the GeoKeyDirectoryTag or CoordRefSysCode argument, accordingly.

  • Check the GeoTIFF specification for values of the following parameters:

    You can also obtain the 'CoordRefSysCode' values from the EPSG data files (pcs.csv and gcs.csv) in the folder:

    matlabroot/toolbox/map/mapproj/projdata/epsg_csv

Introduced before R2006a