Exporting to Images
To export data from the MATLAB® workspace using one of the
standard graphics file formats, use the imwrite
function.
Using this function, you can export data in formats such as the Tagged
Image File Format (TIFF), Joint Photographic Experts Group (JPEG),
and Portable Network Graphics (PNG). For a complete list of supported
formats, see the imwrite
reference
page.
The following example writes a multidimensional array of uint8
data I
from
the MATLAB workspace into a file in TIFF format. The class of
the output image written to the file depends on the format specified.
For most formats, if the input array is of class uint8
, imwrite
outputs
the data as 8-bit values. See the imwrite
reference
page for details.
whos I Name Size Bytes Class I 650x600x3 1170000 uint8 array Grand total is 1170000 elements using 1170000 bytes imwrite(I, 'my_graphics_file.tif','tif');
Note
imwrite
supports different syntaxes for several
of the standard formats. For example, with TIFF file format, you can
specify the type of compression MATLAB uses to store the image.
See the imwrite
reference page
for details.
For more control writing data to a TIFF file, use the Tiff
object—see Exporting Image Data and Metadata to TIFF Files for more
information.
Exporting Image Data and Metadata to TIFF Files
While you can use imwrite
to export image
data and metadata (tags) to Tagged Image File Format (TIFF) files,
the function does have some limitations. For example, when you want
to modify image data or metadata in the file, you must write the all
the data to the file. You cannot write only the updated portion. Using
the Tiff
object, you can write portions of the
image data and modify or add individual tags to a TIFF file. When
you construct a Tiff
object, it represents your
connection with a TIFF file and provides access to many of the routines
in the LibTIFF library.
The following sections provide step-by-step examples of using Tiff
object
methods and properties to perform some common tasks with TIFF files.
To get the most out of the Tiff
object, you must
be familiar with the TIFF specification and technical notes. View
this documentation at LibTIFF - TIFF Library and Utilities.
Creating a New TIFF File
Create some image data. This example reads image data from a JPEG file included with MATLAB:
imgdata = imread('ngc6543a.jpg');
Create a new TIFF file by constructing a
Tiff
object, specifying the name of the new file as an argument. To create a file you must specify either write mode ('w'
) or append mode ('a'
):t = Tiff('myfile.tif','w');
When you create a new TIFF file, the
Tiff
constructor creates a file containing an image file directory (IFD). A TIFF file uses this IFD to organize all the data and metadata associated with a particular image. A TIFF file can contain multiple IFDs. TheTiff
object makes the IFD it creates the current IFD.Tiff
object methods operate on the current IFD. You can navigate among IFDs in a TIFF file and specify which IFD is the current IFD usingTiff
object methods.Set required TIFF tags using the
setTag
method of theTiff
object. These required tags specify information about the image, such as its length and width. To break the image data into strips, specify a value for theRowsPerStrip
tag. To break the image data into tiles, specify values for theTileWidth
andTileLength
tags. The example creates a structure that contains tag names and values and passes that tosetTag
. You also can set each tag individually.tagstruct.ImageLength = size(imgdata,1); tagstruct.ImageWidth = size(imgdata,2); tagstruct.Photometric = Tiff.Photometric.RGB; tagstruct.BitsPerSample = 8; tagstruct.SamplesPerPixel = 3; tagstruct.RowsPerStrip = 16; tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky; tagstruct.Software = 'MATLAB'; tagstruct % display tagstruct setTag(t,tagstruct)
For information about supported TIFF tags and how to set their values, see Setting Tag Values. For example, the
Tiff
object supports properties that you can use to set the values of certain properties. This example uses theTiff
objectPlanarConfiguration
property to specify the correct value for the chunky configuration:Tiff.PlanarConfiguration.Chunky
.Write the image data and metadata to the current directory using the
write
method of theTiff
object.write(t,imgdata);
If you wanted to put multiple images into your file, call the
writeDirectory
method right after performing this write operation. ThewriteDirectory
method sets up a new image file directory in the file and makes this new directory the current directory.Close your connection to the file by closing the
Tiff
object:close(t);
Test that you created a valid TIFF file by using the
imread
function to read the file, and then display the image:imagesc(imread('myfile.tif'));
Writing a Strip or Tile of Image Data
Note
You can only modify a strip or a tile of image data if the data is not compressed.
Open an existing TIFF file for modification by creating a
Tiff
object. This example uses the file created in Creating a New TIFF File. TheTiff
constructor returns a handle to aTiff
object.t = Tiff('myfile.tif','r+');
Generate some data to write to a strip in the image. This example creates a three-dimensional array of zeros that is the size of a strip. The code uses the number of rows in a strip, the width of the image, and the number of samples per pixel as dimensions. The array is an array of
uint8
values.width = getTag(t,'ImageWidth'); height = getTag(t,'RowsPerStrip'); numSamples = getTag(t,'SamplesPerPixel'); stripData = zeros(height,width,numSamples,'uint8');
If the image data had a tiled layout, you would use the
TileWidth
andTileLength
tags to specify the dimensions.Write the data to a strip in the file using the
writeEncodedStrip
method. Specify the index number that identifies the strip you want to modify. The example picks strip 18 because it is easier to see the change in the image.writeEncodedStrip(t,18,stripData);
If the image had a tiled layout, you would use the
writeEncodedTile
method to modify the tile.Close your connection to the file by closing the
Tiff
object.close(t);
Test that you modified a strip of the image in the TIFF file by using the
imread
function to read the file, and then display the image.modified_imgdata = imread('myfile.tif'); imagesc(modified_imgdata)
Note the black strip across the middle of the image.
Modifying TIFF File Metadata (Tags)
Open an existing TIFF file for modification using the
Tiff
object. This example uses the file created in Creating a New TIFF File. TheTiff
constructor returns a handle to aTiff
object.t = Tiff('myfile.tif','r+');
Verify that the file does not contain the
Artist
tag, using thegetTag
method. This code should issue an error message saying that it was unable to retrieve the tag.artist_value = getTag(t,'Artist');
Add the
Artist
tag using thesetTag
method.setTag(t,'Artist','Pablo Picasso');
Write the new tag data to the TIFF file using the
rewriteDirectory
method. Use therewriteDirectory
method when modifying existing metadata in a file or adding new metadata to a file.rewriteDirectory(t);
Close your connection to the file by closing the
Tiff
object.close(t);
Test your work by reopening the TIFF file and getting the value of the
Artist
tag, using thegetTag
method.t = Tiff('myfile.tif', 'r'); getTag(t,'Artist') ans = Pablo Picasso close(t);
Creating TIFF File Subdirectories
Create some image data. This example reads image data from a JPEG file included with MATLAB. The example then creates two reduced-resolution (thumbnail) versions of the image data.
imgdata = imread('ngc6543a.jpg'); % % Reduce number of pixels by a half. img_half = imgdata(1:2:end,1:2:end,:); % % Reduce number of pixels by a third. img_third = imgdata(1:3:end,1:3:end,:);
Create a new TIFF file by constructing a
Tiff
object and specifying the name of the new file as an argument. To create a file you must specify either write mode ('w'
) or append mode ('a'
). TheTiff
constructor returns a handle to aTiff
object.t = Tiff('my_subimage_file.tif','w');
Set required TIFF tags using the
setTag
method of theTiff
object. These required tags specify information about the image, such as its length and width. To break the image data into strips, specify a value for theRowsPerStrip
tag. To break the image data into tiles, use theTileWidth
andTileLength
tags. The example creates a structure that contains tag names and values and passes that tosetTag
. You can also set each tag individually.To create subdirectories, you must set the
SubIFD
tag, specifying the number of subdirectories you want to create. Note that the number you specify isn't the value of theSubIFD
tag. The number tells theTiff
software to create aSubIFD
that points to two subdirectories. The actual value of theSubIFD
tag will be the byte offsets of the two subdirectories.tagstruct.ImageLength = size(imgdata,1); tagstruct.ImageWidth = size(imgdata,2); tagstruct.Photometric = Tiff.Photometric.RGB; tagstruct.BitsPerSample = 8; tagstruct.SamplesPerPixel = 3; tagstruct.RowsPerStrip = 16; tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky; tagstruct.Software = 'MATLAB'; tagstruct.SubIFD = 2 ; % required to create subdirectories tagstruct % display tagstruct setTag(t,tagstruct)
For information about supported TIFF tags and how to set their values, see Setting Tag Values. For example, the
Tiff
object supports properties that you can use to set the values of certain properties. This example uses theTiff
objectPlanarConfiguration
property to specify the correct value for the chunky configuration:Tiff.PlanarConfiguration.Chunky
.Write the image data and metadata to the current directory using the
write
method of theTiff
object.write(t,imgdata);
Set up the first subdirectory by calling the
writeDirectory
method. ThewriteDirectory
method sets up the subdirectory and make the new directory the current directory. Because you specified that you wanted to create two subdirectories,writeDirectory
sets up a subdirectory.writeDirectory(t);
Set required tags, just as you did for the regular directory. According to the LibTIFF API, a subdirectory cannot contain a
SubIFD
tag.tagstruct2.ImageLength = size(img_half,1); tagstruct2.ImageWidth = size(img_half,2); tagstruct2.Photometric = Tiff.Photometric.RGB; tagstruct2.BitsPerSample = 8; tagstruct2.SamplesPerPixel = 3; tagstruct2.RowsPerStrip = 16; tagstruct2.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky; tagstruct2.Software = 'MATLAB'; tagstruct2 % display tagstruct2 setTag(t,tagstruct2)
Write the image data and metadata to the subdirectory using the
write
method of theTiff
object.write(t,img_half);
Set up the second subdirectory by calling the
writeDirectory
method. ThewriteDirectory
method sets up the subdirectory and makes it the current directory.writeDirectory(t);
Set required tags, just as you would for any directory. According to the LibTIFF API, a subdirectory cannot contain a
SubIFD
tag.tagstruct3.ImageLength = size(img_third,1); tagstruct3.ImageWidth = size(img_third,2); tagstruct3.Photometric = Tiff.Photometric.RGB; tagstruct3.BitsPerSample = 8; tagstruct3.SamplesPerPixel = 3; tagstruct3.RowsPerStrip = 16; tagstruct3.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky; tagstruct3.Software = 'MATLAB'; tagstruct3 % display tagstruct3 setTag(t,tagstruct3)
Write the image data and metadata to the subdirectory using the
write
method of theTiff
object:write(t,img_third);
Close your connection to the file by closing the
Tiff
object:close(t);
Setting Tag Values
The following table lists all the TIFF tags that the Tiff
object supports
and includes information about their MATLAB class and size. For certain tags, the table also indicates the set of values
that the Tiff
object supports, which is a subset of all the possible
values defined by the TIFF specification. You can use the Tiff
properties structure to specify the supported values for these tags. For example, use
Tiff.Compression.JPEG
to specify JPEG compression. See the Tiff
reference page for a full list of properties.
Table 1: Supported TIFF Tags
TIFF Tag | Class | Size | Supported Values | Notes |
---|---|---|---|---|
Artist | char | 1xN | ||
BitsPerSample | double | 1x1 | 1,8,16,32,64 | See Table 2 |
ColorMap | double | 256x3 | Values should be normalized between 0–1. Stored internally
as uint16 values. | Photometric must be Palette |
Compression | double | 1x1 | None : 1CCITTRLE :
2CCITTFax3 : 3CCITTFax4 :
4LZW : 5JPEG :
7CCITTRLEW : 32771PackBits :
32773Deflate : 32946AdobeDeflate :
8 | See Table 3. |
Copyright | char | 1xN | ||
DateTime | char | 1x19 | Return value is padded to 19 chars if required. | |
DocumentName | char | 1xN | ||
DotRange | double | 1x2 | Photometric must be Separated | |
ExtraSamples | double | 1xN | Unspecified : 0AssociatedAlpha :
1UnassociatedAlpha : 2 | See Table 4. |
FillOrder | double | 1x1 | ||
GeoAsciiParamsTag | char | 1xN | ||
GeoDoubleParamsTag | double | 1xN | ||
GeoKeyDirectoryTag | double | Nx4 | ||
Group3Options | double | 1x1 | Compression must be CCITTFax3 | |
Group4Options | double | 1x1 | Compression must be CCITTFax4 | |
HalfToneHints | double | 1x2 | ||
HostComputer | char | 1xn | ||
ICCProfile | uint8 | 1xn | ||
ImageDescription | char | 1xn | ||
ImageLength | double | 1x1 | ||
ImageWidth | double | 1x1 | ||
InkNames | char cell array | 1x NumInks | Photometric must be Separated | |
InkSet | double | 1x1 | CMYK : 1MultiInk :
2 | Photometric must be Separated |
JPEGQuality | double | 1x1 | A value between 1 and 100 | |
Make | char | 1xn | ||
MaxSampleValue | double | 1x1 | 0–65,535 | |
MinSampleValue | double | 1x1 | 0–65,535 | |
Model | char | 1xN | ||
ModelPixelScaleTag | double | 1x3 | ||
ModelTiepointTag | double | Nx6 | ||
ModelTransformationMatrixTag | double | 1x16 | ||
NumberOfInks | double | 1x1 | Must be equal to SamplesPerPixel | |
Orientation | double | 1x1 | TopLeft : 1TopRight :
2BottomRight : 3BottomLeft :
4LeftTop : 5RightTop :
6RightBottom : 7LeftBottom :
8 | |
PageName | char | 1xN | ||
PageNumber | double | 1x2 | ||
Photometric | double | 1x1 | MinIsWhite : 0MinIsBlack :
1RGB : 2Palette :
3Mask : 4Separated :
5YCbCr : 6CIELab :
8ICCLab : 9ITULab :
10 | See Table 2. |
Photoshop | uint8 | 1xN | ||
PlanarConfiguration | double | 1x1 | Chunky : 1 Separate :
2 | |
PrimaryChromaticities | double | 1x6 | ||
ReferenceBlackWhite | double | 1x6 | ||
ResolutionUnit | double | 1x1 | ||
RICHTIFFIPTC | uint8 | 1xN | ||
RowsPerStrip | double | 1x1 | ||
RPCCoefficientTag | double | 1x92 | 92-element row vector | See Table 6 |
SampleFormat | double | 1x1 | Uint : 1Int :
2IEEEFP : 3 | See Table 2 |
SamplesPerPixel | double | 1x1 | ||
SMaxSampleValue | double | 1x1 | Range of MATLAB data type specified for Image data | |
SMinSampleValue | double | 1x1 | Range of MATLAB data type specified for Image data | |
Software | char | 1xN | ||
StripByteCounts | double | 1xN | Read-only | |
StripOffsets | double | 1xN | Read-only | |
SubFileType | double | 1x1 | Default : 0ReducedImage :
1Page : 2Mask :
4 | |
SubIFD | double | 1x1 | ||
TargetPrinter | char | 1xN | ||
Thresholding | double | 1x1 | BiLevel : 1 HalfTone :
2 ErrorDiffuse : 3 |
|
TileByteCounts | double | 1xN | Read-only | |
TileLength | double | 1x1 | Must be a multiple of 16 | |
TileOffsets | double | 1xN | Read-only | |
TileWidth | double | 1x1 | Must be a multiple of 16 | |
TransferFunction | double | See note1 | Each value should be within 0–2^16-1 | SamplePerPixel can be either 1 or 3 |
WhitePoint | double | 1x2 | Photometric can be: RGB Palette YCbCr CIELab ICCLab ITULab | |
XMP | char | 1xn | N>5 | |
XPostion | double | 1x1 | ||
XResolution | double | 1x1 | ||
YCbCrCoefficents | double | 1x3 | Photometric must be YCbCr | |
YCbCrPositioning | double | 1x1 | Centered : 1 Cosited :
2 | Photometric must be YCbCr |
YCbCrSubSampling | double | 1x2 | Photometric must be YCbCr | |
YPosition | double | 1x1 | ||
YResolution | double | 1x1 | ||
ZipQuality | double | 1x1 | Value between 1 and 9 |
1Size is 1x2^BitsPerSample
or3x2^BitsPerSample
.
Table 2: Valid SampleFormat Values for BitsPerSample Settings
BitsPerSample | SampleFormat | MATLAB Data Type |
---|---|---|
1 | Uint | logical |
8 | Uint , Int | uint8 , int8 |
16 | Uint , Int | uint16 , int16 |
32 | Uint , Int , IEEEFP | uint32 , int32 , single |
64 | IEEEFP | double |
Table 3: Valid SampleFormat Values for BitsPerSample and Photometric Combinations
BitsPerSample Values | |||||
---|---|---|---|---|---|
Photometric Values | 1 | 8 | 16 | 32 | 64 |
MinIsWhite | Uint | Uint/Int | Uint Int | Uint Int IEEEFP | IEEEFP |
MinIsBlack | Uint | Uint/Int | Uint Int | Uint Int IEEEFP | IEEEFP |
RGB | Uint | Uint | Uint IEEEFP | IEEEFP | |
Pallette | Uint | Uint | |||
Mask | Uint | ||||
Separated | Uint | Uint | Uint IEEEFP | IEEEFP | |
YCbCr | Uint | Uint | Uint IEEEFP | IEEEFP | |
CIELab | Uint | Uint | |||
ICCLab | Uint | Uint | |||
ITULab | Uint | Uint |
Table 4: Valid SampleFormat Values for BitsPerSample and Compression Combinations
BitsPerSample Values | |||||
---|---|---|---|---|---|
Compression Values | 1 | 8 | 16 | 32 | 64 |
None | Uint | Uint Int | Uint Int | Uint Int IEEEFP | IEEEFP |
CCITTRLE | Uint | ||||
CCITTFax3 | Uint | ||||
CCITTFax4 | Uint | ||||
LZW | Uint | Uint Int | Uint Int | Uint Int IEEEFP | IEEEFP |
JPEG | Uint Int | ||||
CCITTRLEW | Uint | ||||
PackBits | Uint | Uint Int | Uint Int | Uint Int IEEEFP | IEEEFP |
Deflate | Uint | Uint Int | Uint Int | Uint Int IEEEFP | IEEEFP |
AdobeDeflate | Uint | Uint Int | Uint Int | Uint Int IEEEFP | IEEEFP |
Table 5: Valid SamplesPerPixel Values for Photometric Settings
Photometric Values | SamplesPerPixel1 |
---|---|
MinIsWhite | 1+ |
MinIsBlack | 1+ |
RGB | 3+ |
Pallette | 1 |
Mask | 1 |
Separated | 1+ |
YCbCr | 3 |
CIELab | 3+ |
ICCLab | 3+ |
ITULab | 3+ |
Table 6: List of RPCCoefficientTag Value Descriptions
Index Value in 92-Element Vector | Value Descriptions1 | Units |
---|---|---|
1 | Root mean square bias error | meters per horizontal axis |
2 | Root mean square random error | meters per horizontal axis |
3 | Line offset | pixels |
4 | Sample offset | pixels |
5 | Geodetic latitude offset | degrees |
6 | Geodetic longitude offset | degrees |
7 | Geodetic height offset | meters |
8 | Line scale factor | pixels |
9 | Sample scale factor | pixels |
10 | Geodetic latitude scale | degrees |
11 | Geodetic longitude scale | degrees |
12 | Geodetic height scale factor | meters |
13 through 32 | Numerator coefficients of r(n), a rational polynomial equation 2 | |
33 through 52 | Denominator coefficients of the rational polynomial equation r(n) | |
53 through 72 | Numerator coefficients of c(n), a rational polynomial equation 2 | |
73 through 92 | Denominator coefficients of the rational polynomial equation c(n) |
1To specify the values in this vector using the
RPCCoefficientTag
object, see
in the Mapping Toolbox™.RPCCoefficientTag
(Mapping Toolbox)
2Equations r(n) and c(n) represent the normalized row and column values of a generic rigorous projection model.