Reading and Writing Image Data Using Matlab
Reading and Writing Image Data Using Matlab

Getting Information About a Graphics File

To obtain information about a graphics file and its contents, use the imfinfo function. You can use imfinfo with any of the formats supported by MATLAB. Use the imformats function to determine which formats are supported.

The information returned by imfinfo depends on the file format, but it always includes at least the following:

  • Name of the file

  • File format

  • Version number of the file format

  • File modification date

  • File size in bytes

  • Image width in pixels

  • Image height in pixels

  • Number of bits per pixel

  • Image type: truecolor (RGB), grayscale (intensity), or indexed

Reading Image Data

To import an image from any supported graphics image file format, in any of the supported bit depths, use the imread function. This example reads a truecolor image into the MATLAB workspace as the variable RGB.

RGB = imread('football.jpg');

If the image file format uses 8-bit pixels, imread stores the data in the workspace as a uint8 array. For file formats that support 16-bit data, such as PNG and TIFF, imread creates a uint16 array.

imread uses two variables to store an indexed image in the workspace: one for the image and another for its associated colormap. imread always reads the colormap into a matrix of class double, even though the image array itself may be of class uint8 or uint16.

[X,map] = imread('trees.tif');

In these examples, imread infers the file format to use from the contents of the file. You can also specify the file format as an argument to imread. imread supports many common graphics file formats, such as Microsoft® Windows® Bitmap (BMP), Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG), Portable Network Graphics (PNG), and Tagged Image File Format (TIFF) formats. For the latest information concerning the bit depths and/or image formats supported, see imread and imformats.

If the graphics file contains multiple images, imread imports only the first image from the file. To import additional images, you must use imread with format-specific arguments to specify the image you want to import. In this example, imread imports a series of 27 images from a TIFF file and stores the images in a four-dimensional array. You can use imfinfo to determine how many images are stored in the file.

mri = zeros([128 128 1 27],'uint8'); % preallocate 4-D array for frame=1:27 [mri(:,:,:,frame),map] = imread('mri.tif',frame); end

When a file contains multiple images that are related in some way, you can call image processing algorithms directly. For more information, see Working with Image Sequences.

If you are working with a large file, you may want to try block processing to reduce memory usage. For more information, see Neighborhood or Block Processing: An Overview.

Writing Image Data to a File

Overview

To export image data from the MATLAB workspace to a graphics file in one of the supported graphics file formats, use the imwrite function. When using imwrite, you specify the MATLAB variable name and the name of the file. If you include an extension in the filename, imwrite attempts to infer the desired file format from it. For example, the file extension .jpg infers the Joint Photographic Experts Group (JPEG) format. You can also specify the format explicitly as an argument to imwrite.

This example loads the indexed image X from a MAT-file, clown.mat, along with the associated colormap map, and then exports the image as a bitmap (BMP) file.

load clown whos Name Size Bytes Class X 200x320 512000 double array caption 2x1 4 char array map 81x3 1944 double array Grand total is 64245 elements using 513948 bytes imwrite(X,map,'clown.bmp')

Specifying Format-Specific Parameters

When using imwrite with some graphics formats, you can specify additional format-specific parameters. For example, with PNG files, you can specify the bit depth. This example writes a grayscale image I to a 4-bit PNG file.

imwrite(I,'clown.png','BitDepth',4);

This example writes an image A to a JPEG file, using an additional parameter to specify the compression quality parameter.

imwrite(A, 'myfile.jpg', 'Quality', 100);

For more information about these additional format-specific syntaxes, see the imwrite reference page.

Reading and Writing Binary Images in 1-Bit Format

In certain file formats, such as TIFF, a binary image can be stored in a 1-bit format. When you read in a binary image in 1-bit format, imread stores the data in the workspace as a logical array. If the file format supports it, imwrite writes binary images as 1-bit images by default. This example reads in a binary image and writes it as a TIFF file.

BW = imread('text.png');  imwrite(BW,'test.tif'); 

To verify the bit depth of test.tif, call imfinfo and check the BitDepth field.

info = imfinfo('test.tif');    info.BitDepth  ans =         1

Note   When writing binary files, MATLAB sets the ColorType field to 'grayscale'.

Determining the Storage Class of the Output File

imwrite uses the following rules to determine the storage class used in the output image.

Storage Class of Image Storage Class of Output Image File

logical

If the output image file format supports 1-bit images, imwrite creates a 1-bit image file.

If the output image file format specified does not support 1-bit images, imwrite exports the image data as a uint8 grayscale image.

uint8

If the output image file format supports unsigned 8-bit images, imwrite creates an unsigned 8-bit image file.

uint16

If the output image file format supports unsigned 16-bit images (PNG or TIFF), imwrite creates an unsigned 16-bit image file.

If the output image file format does not support 16-bit images, imwrite scales the image data to class uint8 and creates an 8-bit image file.

int16

Partially supported; depends on file format.

single

Partially supported; depends on file format.

double

MATLAB scales the image data to uint8 and creates an 8-bit image file, because most image file formats use 8 bits.


Converting Between Graphics File Formats

To change the graphics format of an image, use imread to import the image into the MATLAB workspace and then use the imwrite function to export the image, specifying the appropriate file format.

To illustrate, this example uses the imread function to read an image in TIFF format into the workspace and write the image data as JPEG format.

moon_tiff = imread('moon.tif');  imwrite(moon_tiff,'moon.jpg');

For the specifics of which bit depths are supported for the different graphics formats, and for how to specify the format type when writing an image to file, see the reference pages for imread and imwrite.

Working with DICOM Files

Overview of DICOM Support

The Digital Imaging and Communications in Medicine (DICOM) Standard is a joint project of the American College of Radiology (ACR) and the National Electrical Manufacturers Association (NEMA). The standard facilitates interoperability of medical imaging equipment by specifying a set of media storage services, a file format, and a medical directory structure to facilitate access to the images and related information stored on interchange media. For detailed information about the standard, see the official DICOM web site.

MATLAB provides the following support for working with files in the DICOM format:

  • Reading any file that complies with the DICOM standard

  • Writing three different types of DICOM files, or DICOM information objects (IOD), with validation:

    • Secondary capture (default)

    • Magnetic resonance

    • Computed tomography

  • Writing many more types of DICOM files without validation, by setting the createmode flag to 'copy' when writing data to a file.

    Note   MATLAB supports working with DICOM files. There is no support for working with DICOM network capabilities.

Reading Metadata from a DICOM File

DICOM files contain metadata that provide information about the image data, such as the size, dimensions, bit depth, modality used to create the data, and equipment settings used to capture the image. To read metadata from a DICOM file, use the dicominfo function. dicominfo returns the information in a MATLAB structure where every field contains a specific piece of DICOM metadata. You can use the metadata structure returned by dicominfo to specify the DICOM file you want to read using dicomread — see Reading Image Data from a DICOM File.

The following example reads the metadata from a sample DICOM file that is included with the toolbox.

info = dicominfo('CT-MONO2-16-ankle.dcm') info = Filename: [1x89 char] FileModDate: '18-Dec-2000 11:06:43' FileSize: 525436 Format: 'DICOM' FormatVersion: 3 Width: 512 Height: 512 BitDepth: 16 ColorType: 'grayscale' FileMetaInformationGroupLength: 192 FileMetaInformationVersion: [2x1 uint8] MediaStorageSOPClassUID: '1.2.840.10008.5.1.4.1.1.7' MediaStorageSOPInstanceUID: [1x50 char] TransferSyntaxUID: '1.2.840.10008.1.2' ImplementationClassUID: '1.2.840.113619.6.5' . . .

Handling Private Metadata

The DICOM specification defines many of these metadata fields, but files can contain additional fields, called private metadata. This private metadata is typically defined by equipment vendors to provide additional information about the data they provide.

When dicominfo encounters a private metadata field in a DICOM file, it returns the metadata creating a generic name for the field based on the group and element tags of the metadata. For example, if the file contained private metadata at group 0009 and element 0006, dicominfo creates the name:Private_0009_0006. dicominfo attempts to interpret the private metadata, if it can. For example, if the metadata is a text string, dicominfo processes the data. If it can't interpret the data, dicominfo returns a sequence of bytes.

If you need to process a DICOM file created by a manufacturer that uses private metadata, and you prefer to view the correct name of the field as well as the data, you can create your own copy of the DICOM data dictionary and update it to include definitions of the private metadata. You will need information about the private metadata that vendors typically provide in DICOM compliance statements. For more information about updating DICOM dictionary, see Creating Your Own Copy of the DICOM Dictionary.

Creating Your Own Copy of the DICOM Dictionary

MathWorks uses a DICOM dictionary that contains definitions of thousands of standard DICOM metadata fields. If your DICOM file contains metadata that is not defined this dictionary, you can update the dictionary, creating your own copy that it includes these private metadata fields.

To create your own dictionary, perform this procedure:

  1. Make a copy of the text version of the DICOM dictionary that is included with MATLAB. This file, called dicom-dict.txt is located in matlabroot/toolbox/images/medformats or matlabroot/toolbox/images/iptformats depending on which version of the Image Processing Toolbox software you are working with. Do not attempt to edit the MAT-file version of the dictionary, dicom-dict.mat.

  2. Edit your copy of the DICOM dictionary, adding entries for the metadata. Insert the new metadata field using the group and element tag, type, and other information. Follow the format of the other entries in the file. The creator of the metadata (e.g., an equipment vendor) must provide you with the information.

  3. Save your copy of the dictionary.

  4. Set MATLAB to use your copy of the DICOM dictionary, dicomdict function.

Reading Image Data from a DICOM File

To read image data from a DICOM file, use the dicomread function. The dicomread function reads files that comply with the DICOM specification but can also read certain common noncomplying files.

When using dicomread, you can specify the filename as an argument, as in the following example. The example reads the sample DICOM file that is included with the toolbox.

I = dicomread('CT-MONO2-16-ankle.dcm');

You can also use the metadata structure returned by dicominfo to specify the file you want to read, as in the following example.

info = dicominfo('CT-MONO2-16-ankle.dcm');  I = dicomread(info);

Viewing Images from DICOM Files

To view the image data imported from a DICOM file, use one of the toolbox image display functions imshow or imtool. Note, however, that because the image data in this DICOM file is signed 16-bit data, you must use the autoscaling syntax with either display function to make the image viewable.

imshow(I,'DisplayRange',[])

Writing Image Data or Metadata to a DICOM File

To write image data or metadata to a file in DICOM format, use the dicomwrite function. This example writes the image I to the DICOM file ankle.dcm.

dicomwrite(I,'ankle.dcm')

Writing Metadata with the Image Data

When writing image data to a DICOM file, dicomwrite automatically includes the minimum set of metadata fields required by the type of DICOM information object (IOD) you are creating. dicomwrite supports the following DICOM IODs with full validation.

  • Secondary capture (default)

  • Magnetic resonance

  • Computed tomography

dicomwrite can write many other types of DICOM data (e.g., X-ray, radiotherapy, nuclear medicine) to a file; however, dicomwrite does not perform any validation of this data. See dicomwrite for more information.

You can also specify the metadata you want to write to the file by passing to dicomwrite an existing DICOM metadata structure that you retrieved using dicominfo. In the following example, the dicomwrite function writes the relevant information in the metadata structure info to the new DICOM file.

info = dicominfo('CT-MONO2-16-ankle.dcm'); I = dicomread(info); dicomwrite(I,'ankle.dcm',info)

Note that the metadata written to the file is not identical to the metadata in the info structure. When writing metadata to a file, there are certain fields that dicomwrite must update. To illustrate, look at the instance ID in the original metadata and compare it with the ID in the new file.

info.SOPInstanceUID ans = 1.2.840.113619.2.1.2411.1031152382.365.1.736169244

Now, read the metadata from the newly created DICOM file, using dicominfo, and check the SOPInstanceUID field.

info2 = dicominfo('ankle.dcm'); info2.SOPInstanceUID ans = 1.2.841.113411.2.1.2411.10311244477.365.1.63874544

Note that the instance ID in the newly created file differs from the ID in the original file.

Understanding Explicit Versus Implicit VR Attributes

DICOM attributes provide the length and then the data. When writing data to a file, you can include a two-letter value representation (VR) with the attribute or you can let DICOM infer the value representation from the data dictionary. When you specify the VR option with the value 'explicit', the dicomwrite function includes the VR in the attribute. The following figure shows the attributes with and without the VR.

Removing Confidential Information from a DICOM File

When using a DICOM file as part of a training set, blinded study, or a presentation, you might want to remove confidential patient information, a process called anonymizing the file. To do this, use the dicomanon function.

The dicomanon function creates a new series with new study values, changes some of the metadata, and then writes the file. For example, you could replace steps 4, 5, and 6 in the example in Example: Creating a New DICOM Series with a call to the dicomanon function.

Example: Creating a New DICOM Series

When writing a modified image to a DICOM file, you might want to make the modified image the start of a new series. In the DICOM standard, images can be organized into series. When you write an image with metadata to a DICOM file, dicomwrite puts the image in the same series by default. To create a new series, you must assign a new DICOM unique identifier to the SeriesInstanceUID metadata field. The following example illustrates this process.

  1. Read an image from a DICOM file into the MATLAB workspace.

    I = dicomread('CT-MONO2-16-ankle.dcm');

    To view the image, use either of the toolbox display functions imshow or imtool. Because the DICOM image data is signed 16-bit data, you must use the autoscaling syntax.

    imtool(I,'DisplayRange',[])

  2. Read the metadata from the same DICOM file.

    info = dicominfo('CT-MONO2-16-ankle.dcm');

    To identify the series an image belongs to, view the value of the SeriesInstanceUID field.

    info.SeriesInstanceUID ans = 1.2.840.113619.2.1.2411.1031152382.365.736169244

  3. You typically only start a new DICOM series when you modify the image in some way. This example removes all the text from the image.

    The example finds the maximum and minimum values of all pixels in the image. The pixels that form the white text characters are set to the maximum pixel value.

    max(I(:))  ans =        4080    min(I(:))    ans =        32

    To remove these text characters, the example sets all pixels with the maximum value to the minimum value.

    Imodified = I;  Imodified(Imodified == 4080) = 32;

    View the processed image.

    imshow(Imodified,[])

  4. Generate a new DICOM unique identifier (UID) using the dicomuid function. You need a new UID to write the modified image as a new series.

    uid = dicomuid uid = 1.3.6.1.4.1.9590.100.1.1.56461980611264497732341403390561061497

    dicomuid is guaranteed to generate a unique UID.

  5. Set the value of the SeriesInstanceUID field in the metadata associated with the original DICOM file to the generated value.

    info.SeriesInstanceUID = uid;
  6. Write the modified image to a new DICOM file, specifying the modified metadata structure, info, as an argument. Because you set the SeriesInstanceUID value, the image you write is part of a new series.
    dicomwrite(Imodified,'ankle_newseries.dcm',info);

    To verify this operation, view the image and the SeriesInstanceUID metadata field in the new file.

For information about the syntax variations that specify nondefault spatial coordinates, see the reference page for imshow.

Working with Mayo Analyze 7.5 Files

Analyze 7.5 is a file format, developed by the Mayo Clinic, for storing MRI data. An Analyze 7.5 data set consists of two files:

  • Header file (filename.hdr) — Provides information about dimensions, identification, and processing history. You use the analyze75info function to read the header information.

  • Image file (filename.img) — Image data, whose data type and ordering are described by the header file. You use analyze75read to read the image data into the MATLAB workspace.

    Note   The Analyze 7.5 format uses the same dual-file data set organization and the same filename extensions as the Interfile format; however, the file formats are not interchangeable. To learn how to read data from an Interfile data set, see Working with Interfile Files.

The following example calls the analyze75info function to read the metadata from the Analyze 7.5 header file. The example then passes the info structure returned by analyze75info to the analyze75read function to read the image data from the image file.

info = analyze75info('brainMRI.hdr');  X = analyze75read(info);

Working with Interfile Files

Interfile is a file format that was developed for the exchange of nuclear medicine image data.

An Interfile data set consists of two files:

  • Header file (filename.hdr) — Provides information about dimensions, identification and processing history. You use the interfileinfo function to read the header information.

  • Image file (filename.img) — Image data, whose data type and ordering are described by the header file. You use interfileread to read the image data into the MATLAB workspace.

    Note   The Interfile format uses the same dual-file data set organization and the same filename extensions as the Analyze 7.5 format; however, the file formats are not interchangeable. To learn how to read data from an Analyze 7.5 data set, see Working with Mayo Analyze 7.5 Files.

The following example calls the interfileinfo function to read the metadata from an Interfile header file. The example then reads the image data from the corresponding image file in the Interfile data set. The file used in the example can be downloaded from the Interfile Archive maintained by the Department of Medical Physics and Bioengineering, University College, London, UK.

info = interfileinfo('dyna');  X = interfileread('dyna');

Working with High Dynamic Range Images

Overview

Dynamic range refers to the range of brightness levels, from dark to light. The dynamic range of real-world scenes can be quite high. High Dynamic Range (HDR) images attempt to capture the whole tonal range of real-world scenes (called scene-referred), using 32-bit floating-point values to store each color channel. HDR images contain a high level of detail, close to the range of human vision. The toolbox includes functions for reading, creating, and writing HDR images, and a tone-map operator for displaying HDR images on a computer monitor.

Reading a High Dynamic Range Image

To read a high dynamic range image into the MATLAB workspace, use the hdrread function.

hdr_image = hdrread('office.hdr');

The output image hdr_image is an m-by-n-by-3 image of type single.

whos Name Size Bytes Class Attributes hdr_image 665x1000x3 7980000 single

Note, however, that before you can display a high dynamic range image, you must convert it to a dynamic range appropriate to a computer display, a process called tone mapping. Tone mapping algorithms scale the dynamic range down while attempting to preserve the appearance of the original image. For more information, see Viewing a High Dynamic Range Image.

Creating a High Dynamic Range Image

To create a high dynamic range image from a group of low dynamic range images, use the makehdr function. Note that the low dynamic range images must be spatially registered and the image files must contain EXIF metadata. Specify the low-dynamic range images in a cell array.

hdr_image = makehdr(files);

Viewing a High Dynamic Range Image

If you try to view a HDR image using imshow, the image does not display correctly.

To view an HDR image, you must first convert the data to a dynamic range that can be displayed correctly on a computer. Use the tonemap function to perform this conversion. tonemap converts the high dynamic range image into an RGB image of class uint8.

rgb = tonemap(hdr_image); whos Name Size Bytes Class Attributes hdr_image 665x1000x3 7980000 single rgb 665x1000x3 1995000 uint8

After converting the HDR image, try to display the image again.

imshow(rgb);

Writing a High Dynamic Range Image to a File

To write a high dynamic range image from the MATLAB workspace into a file, use the hdrwrite function.

hdrwrite(hdr,'filename');

Source: http://www.mathworks.com