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 uint8imwrite 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
  1. Create some image data. This example reads image data from a JPEG file included with MATLAB:

    imgdata = imread('ngc6543a.jpg');
  2. 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. The Tiff 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 using Tiff object methods.

  3. Set required TIFF tags using the setTag method of the Tiff 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 the RowsPerStrip tag. To break the image data into tiles, specify values for the TileWidth and TileLength tags. The example creates a structure that contains tag names and values and passes that to setTag. 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'
    t.setTag(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 the Tiff object PlanarConfigurationproperty to specify the correct value for the chunky configuration: Tiff.PlanarConfiguration.Chunky.

  4. Write the image data and metadata to the current directory using the write method of the Tiff object.

    t.write(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.

  5. Close your connection to the file by closing the Tiff object:

    t.close();
    
  6. 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.

  1. Open an existing TIFF file for modification by creating a Tiff object. This example uses the file created in Creating a New TIFF File. The Tiff constructor returns a handle to a Tiff object.

    t = Tiff('myfile.tif','r+');
  2. 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 = t.getTag('ImageWidth');
    height = t.getTag('RowsPerStrip');
    numSamples = t.getTag('SamplesPerPixel');
    stripData = zeros(height,width,numSamples,'uint8');
    

    If the image data had a tiled layout, you would use the TileWidth and TileLength tags to specify the dimensions.

  3. 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.

    t.writeEncodedStrip(18, stripData);
    

    If the image had a tiled layout, you would use the writeEncodedTile method to modify the tile.

  4. Close your connection to the file by closing the Tiff object.

    t.close();
    
  5. 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)
  1. 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 a Tiff object.

    t = Tiff('myfile.tif','r+');
  2. Verify that the file does not contain the Artist tag, using the getTag method. This code should issue an error message saying that it was unable to retrieve the tag.

    artist_value = t.getTag('Artist');
  3. Add the Artist tag using the setTag method.

    t.setTag('Artist','Pablo Picasso');
  4. Write the new tag data to the TIFF file using the rewriteDirectory method. Use the rewriteDirectory method when modifying existing metadata in a file or adding new metadata to a file.

    t.rewriteDirectory();
  5. Close your connection to the file by closing the Tiff object.

    t.close();
    
  6. Test your work by reopening the TIFF file and getting the value of the Artist tag, using the getTag method.

    t = Tiff('myfile.tif', 'r');
    
    t.getTag('Artist')
    
    ans =
    
    Pablo Picasso
    
    t.close();
Creating Subdirectories in a TIFF File
  1. 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,:);
  2. 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'). The Tiff constructor returns a handle to a Tiff object.

    t = Tiff('my_subimage_file.tif','w');
  3. Set required TIFF tags using the setTag method of the Tiff 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 the RowsPerStrip tag. To break the image data into tiles, use the TileWidth and TileLength 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 the SubIFD tag. The number tells the Tiff software to create a SubIFD that points to two subdirectories. The actual value of the SubIFD 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
    t.setTag(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 the Tiff object PlanarConfigurationproperty to specify the correct value for the chunky configuration: Tiff.PlanarConfiguration.Chunky.

  4. Write the image data and metadata to the current directory using the write method of the Tiff object.

    t.write(imgdata);
    
  5. Set up the first subdirectory by calling the writeDirectory method. The writeDirectory method sets up the subdirectory and make the new directory the current directory. Because you specified that you wanted to create two subdirectories, writeDirectorysets up a subdirectory.

    t.writeDirectory();
    
  6. 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'
    t.setTag(tagstruct2)
  7. Write the image data and metadata to the subdirectory using the write method of the Tiff object.

    t.write(img_half);
    
  8. Set up the second subdirectory by calling the writeDirectory method. The writeDirectory method sets up the subdirectory and makes it the current directory.

    t.writeDirectory();
    
  9. 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'
    t.setTag(tagstruct3)
  10. Write the image data and metadata to the subdirectory using the write method of the Tiff object:

    t.write(img_third);
    
  11. Close your connection to the file by closing the Tiff object:

    t.close();
    
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 Tiff object properties to specify the supported values for these tags. For example, useTiff.Compression.JPEG to specify JPEG compression. See the Tiff class 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 asuint16 values. Photometric must bePalette
Compression double 1x1 None: 1
CCITTRLE: 2
CCITTFax3: 3
CCITTFax4: 4
LZW: 5
JPEG: 7
CCITTRLEW: 32771
PackBits: 32773
Deflate: 32946
AdobeDeflate: 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 beSeparated
ExtraSamples double 1xN Unspecified: 0
AssociatedAlpha: 1
UnassociatedAlpha: 2
See Table 4.
FillOrder double 1x1

GeoAsciiParamsTag char 1xN

GeoDoubleParamsTag double 1xN

GeoKeyDirectoryTag double Nx4

Group3Options double 1x1
Compression must beCCITTFax3
Group4Options double 1x1
Compression must beCCITTFax4
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 beSeparated
InkSet double 1x1 CMYK: 1
MultiInk: 2
Photometric must beSeparated
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 toSamplesPerPixel
Orientation double 1x1 TopLeft: 1
TopRight: 2
BottomRight: 3
BottomLeft: 4
LeftTop: 5
RightTop: 6
RightBottom: 7
LeftBottom: 8

PageName char 1xN

PageNumber double 1x2

Photometric double 1x1 MinIsWhite: 0
MinIsBlack: 1
RGB: 2
Palette: 3
Mask: 4
Separated: 5
YCbCr: 6
CIELab: 8
ICCLab: 9
ITULab: 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

SampleFormat double 1x1 Uint: 1
Int: 2
IEEEFP: 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 : 0
ReducedImage: 1
Page: 2
Mask: 4

SubIFD double 1x1

TargetPrinter char 1xN

Thresholding double 1x1 BiLevel: 1 
HalfTone: 2 
ErrorDiffuse: 3

Photometric can be either:MinIsWhite MinIsBlack

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 beYCbCr
YCbCrPositioning double 1x1 Centered: 1 
Cosited: 2
Photometric must beYCbCr
YCbCrSubSampling double 1x2
Photometric must beYCbCr
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 UintInt uint8int8
16 UintInt uint16int16
32 UintIntIEEEFP uint32int32single
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+

1 When you specify more than the expected number of samples per pixel (n+), you must set the ExtraSamples tag accordingly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值