Read image from graphics file
collapse all in page
Syntax
A = imread(filename)
A = imread(filename,fmt)
A = imread(___,idx)
A = imread(___,Name,Value)
[A,map]= imread(___)
[A,map,transparency]= imread(___)
Description
example
A = imread(filename)
readsthe image from the file specified by filename
,inferring the format of the file from its contents. If filename
isa multi-image file, then imread
reads the firstimage in the file.
A = imread(filename,fmt)
additionallyspecifies the format of the file with the standard file extensionindicated by fmt
. If imread
cannotfind a file with the name specified by filename
,it looks for a file named filename.fmt
.
A = imread(___,idx)
reads the specified image or images from a multi-image file. This syntax applies only to GIF, PGM, PBM, PPM, CUR, ICO, TIF, SVS, and HDF4 files. You must specify a filename input, and you can optionally specify fmt.
example
A = imread(___,Name,Value)
specifiesformat-specific options using one or more name-value pair arguments,in addition to any of the input arguments in the previous syntaxes.
example
[A,map]= imread(___)
reads the indexed image in filename
into A
andreads its associated colormap into map
. Colormapvalues in the image file are automatically rescaled into the range [0,1]
.
example
[A,map,transparency]= imread(___)
additionally returns the imagetransparency. This syntax applies only to PNG, CUR, and ICO files.For PNG files, transparency
is the alpha channel,if one is present. For CUR and ICO files, it is the AND (opacity)mask.
Examples
collapse all
Read and Display Image
Open Live Script
Read a sample image.
A = imread('ngc6543a.jpg');
imread
returns a 650-by-600-by-3 array, A
.
Display the image.
image(A)
Convert Indexed Image to RGB
Open Live Script
Read the first image in the sample indexed image file, corn.tif
.
[X,cmap] = imread('corn.tif');
The indexed image X
is a 415-by-312 array of type uint8
. The colormap cmap
is a 256-by-3 matrix of type double
, therefore there are 256 colors in the indexed image. Display the image.
imshow(X,cmap)
Convert the indexed image to an RGB image. The result is a 415-by-312-by-3 array of type double
.
RGB = ind2rgb(X,cmap);
Check that values of the RGB image are in the range [0, 1].
disp(['Range of RGB image is [',num2str(min(RGB(:))),', ',num2str(max(RGB(:))),'].'])
Range of RGB image is [0.0078431, 0.97647].
Read Specific Image in Multipage TIFF File
Open Live Script
Read the third image in the sample file, corn.tif
.
[X,map] = imread('corn.tif',3);
Return Alpha Channel of PNG Image
Return the alpha channel of the sample image, peppers.png
.
[X,map,alpha] = imread('peppers.png');whos alpha
Name Size Bytes Class Attributes alpha 0x0 0 double
No alpha channel is present, so alpha
is empty.
Read Specified Region of TIFF Image
Open Live Script
Read a specific region of pixels of the sample image, corn.tif
.
Specify the 'PixelRegion'
parameter with a cell array of vectors indicating the boundaries of the region to read. The first vector specifies the range of rows to read, and the second vector specifies the range of columns to read.
A = imread('corn.tif','PixelRegion',{[1,2],[2,5]});
imread
reads the image data in rows 1-2 and columns 2-5 from corn.tif
and returns the 2-by-4 array, A
.
Input Arguments
collapse all
filename
— Name of graphics file
character vector | string scalar
Name of graphics file, specified as a character vector or string scalar.
Depending on the location of your file, filename
can take on one of these forms.
Location | Form | ||||||||
---|---|---|---|---|---|---|---|---|---|
Current folder or folder on the MATLAB® path | Specify the name of the file in Example: | ||||||||
File in a folder | If the file is not in the current folder or in a folder on the MATLAB path, then specify the full or relative path name. Example: Example: | ||||||||
URL | If the file is located by an internet URL, then Example: | ||||||||
Remote Location | If the file is stored at a remote location, then
Based on the remote location,
For more information, see Work with Remote Data. Example: |
For information on the bit depths, compression schemes, and color spaces supported for each file type, see Algorithms.
Data Types: char
| string
fmt
— Image format
character vector | string scalar
Image format, specified as a character vector or string scalar indicating the standard file extension. Call imformats
to see a list of supported formats and their file extensions.
Example: 'png'
Data Types: char
| string
idx
— Image to read
integer scalar | vector of integers
Image to read, specified as an integer scalar or, for GIF files,a vector of integers. For example, if idx
is 3,then imread
returns the third image in the file.For a GIF file, if idx
is 1:5
,then imread
returns only the first five frames.The idx
argument is supported only for multi-imageGIF, CUR, ICO, and HDF4 files.
When reading multiple frames from the same GIF file, specify idx
asa vector of frames or use the 'Frames','all'
name-valuepair argument. Because of the way that GIF files are structured, thesesyntaxes provide faster performance compared to calling imread
ina loop.
For HDF4 files, idx
corresponds to the referencenumber of the image to read. Reference numbers do not necessarilycorrespond to the order of the images in the file. You can use imfinfo
tomatch image order with reference number.
Example: 3
Data Types: double
Name-Value Arguments
Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN
, where Name
is the argument name and Value
is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose Name
in quotes.
Example: 'Index',5
reads the fifth image ofa TIFF file.
GIF Files
collapse all
Frames
— Frame to read
1 (default) | positive integer | vector of integers | 'all'
Frames to read, specified as the comma-separated pair consistingof 'Frames'
and a positive integer, a vector ofintegers, or 'all'
. For example, if you specifythe value 3, imread
reads the third frame inthe file. If you specify 'all'
, then imread
readsall frames and returns them in the order in which they appear in thefile.
Example: 'frames',5
JPEG 2000 Files
collapse all
PixelRegion
— Subimage to read
cell array in the form {rows,cols}
Subimage to read, specified as the comma-separated pair consistingof 'PixelRegion'
and a cell array of the form {rows,cols}
.The rows
input specifies the range of rows to read.The cols
input specifies the range of columns toread. Both rows
and cols
mustbe two-element vectors containing 1-based indices. For example, 'PixelRegion',{[12],[3 4]}
reads the subimage bounded by rows 1 and 2 andcolumns 3 and 4 in the image data. If the 'ReductionLevel'
valueis greater than 0, then rows
and cols
arecoordinates of the subimage.
Example: 'PixelRegion',{[1 100],[4 500]}
ReductionLevel
— Reduction of image resolution
0 (default) | nonnegative integer
Reduction of the image resolution, specified as the comma-separatedpair consisting of 'ReductionLevel'
and a nonnegativeinteger. For reduction level L, the image resolutionis reduced by a factor of 2^L. The reduction levelis limited by the total number of decomposition levels as specifiedby the'WaveletDecompositionLevels'
field in theoutput of the imfinfo function.
Example: 'ReductionLevel',5
Data Types: single
| double
V79Compatible
— Compatibility with MATLAB 7.9 (R2009b) and earlier
false
(default) | true
Compatibility with MATLAB 7.9 (R2009b) and earlier, specifiedas the comma-separated pair consisting of 'V79Compatible'
andeither true
or false
. If youspecify true
, then the returned grayscale or RGBimage is consistent with previous versions of imread
(MATLAB 7.9(R2009b) and earlier).
Example: 'V79Compatible',true
Data Types: logical
PNG Files
collapse all
BackgroundColor
— Background color
'none'
| integer | 3-element vector of integers
Background color, specified as 'none'
, aninteger, or a three-element vector of integers. If BackgroundColor
is 'none'
,then imread
does not perform any compositing.Otherwise, imread
blends transparent pixels withthe background color.
If the input image is indexed, then the value of
BackgroundColor
mustbe an integer in the range[1,P]
, whereP
isthe colormap length.If the input image is grayscale, then the value of
BackgroundColor
mustbe an integer in the range[0,1]
.If the input image is RGB, then the value of
BackgroundColor
mustbe a three-element vector with values in the range[0,1]
.
The default value for BackgroundColor
dependson the presence of the transparency
output argumentand the image type:
If you request the
transparency
outputargument, then the default value ofBackgroundColor
is'none'
.If you do not request the
transparency
outputand the PNG file contains a background color chunk, then that coloris the default value forBackgroundColor
.If you do not request the
transparency
outputand the file does not contain a background color chunk, then the defaultvalue forBackgroundColor
is1
forindexed images,0
for grayscale images, and[00 0]
for truecolor (RGB) images.
TIFF Files
collapse all
Index
— Image to read
1 (default) | positive integer
Image to read, specified as the comma-separated pair consistingof 'Index'
and a positive integer. For example,if the value of Index
is 3, then imread
readsthe third image in the file.
Data Types: single
| double
Info
— Information about image
structure array
Information about the image, specified as the comma-separatedpair consisting of 'Info'
and a structure arrayreturned by the imfinfo
function. Use the Info
name-valuepair argument to help imread
locate the imagesin a multi-image TIFF file more quickly.
Data Types: struct
PixelRegion
— Region boundary
cell array
Region boundary, specified as the comma-separated pair consistingof 'PixelRegion'
and a cell array of the form {rows,cols}
.The rows
input specifies the range of rows to read.The cols
input specifies the range of columns toread. rows
and cols
must beeither two-element or three-element vectors of 1-based indices. Atwo-element vector specifies the first and last rows or columns toread. For example, 'PixelRegion',{[1 2],[3 4]}
readsthe region bounded by rows 1 and 2 and columns 3 and 4 in the imagedata.
A three-element vector must be in the form [start incrementstop]
, where start
is the first row orcolumn to read, increment
is an incremental value,and stop
is the last row or column to read. Thissyntax allows image downsampling. For example, 'PixelRegion',{[12 10],[4 3 12]}
reads the region bounded by rows 1 and 10and columns 4 and 12, and samples data from every 2 pixels in thevertical direction, and every 3 pixels in the horizontal direction.
Example: 'PixelRegion',{[1 100],[4 500]}
Data Types: cell
Output Arguments
collapse all
A
— Image data
array
Image data, returned as an array.
If the file contains a grayscale image, then A isan
m
-by-n
array.If the file contains an indexed image, then A is an
m
-by-n
arrayof index values corresponding to the color at that index inmap
.If the file contains a truecolor image, then A isan
m
-by-n
-by-3 array.If the file is a TIFF file containing color imagesthat use the CMYK color space, then A is an
m
-by-n
-by-4array.
The class of A
depends on the image formatand the bit depth of the image data. For more information, see Algorithms
map
— Colormap
m
-by-3 matrix
Colormap associated with the indexed image data in A
,returned as an m
-by-3 matrix of class double
.
transparency
— Transparency information
matrix
Transparency information, returned as a matrix. For PNG files, transparency
is the alpha channel, if present. If no alpha channel is present, or if you specify the 'BackgroundColor'
name-value pair argument, then transparency
is empty. For CUR and ICO files, transparency
is the AND mask. For cursor files, this mask sometimes contains the only useful data.
More About
collapse all
Bit Depth
Bit depth is the number of bits used to representeach image pixel.
Bit depth is calculated by multiplying the bits-per-sample withthe samples-per-pixel. Thus, a format that uses 8 bits for each colorcomponent (or sample) and three samples per pixel has a bit depthof 24. Sometimes the sample size associated with a bit depth can beambiguous. For example, does a 48-bit bit depth represent six 8-bitsamples, four 12-bit samples, or three 16-bit samples? See Algorithms for sample size informationto avoid this ambiguity.
Algorithms
collapse all
For most image file formats, imread
uses8 or fewer bits per color plane to store image pixels. This tablelists the class of the returned image array, A
,for the bit depths used by the file formats.
Bit Depth in File | Classof Array Returned by |
---|---|
1 bit per pixel |
|
2 to 8 bits per color plane |
|
9 to 16 bits per pixel |
For the 16-bit BMP packedformat (5-6-5), MATLAB returns |
The following sections provide information about the supportfor specific formats, listed in alphabetical order by format name.
BMP — Windows Bitmap | JPEG — Joint Photographic Experts Group | PNG — Portable Network Graphics |
CUR — Cursor File | JPEG 2000 — Joint Photographic Experts Group 2000 | PPM — Portable Pixmap |
GIF — Graphics Interchange Format | PBM — Portable Bitmap | RAS — Sun Raster |
HDF4 — Hierarchical Data Format | PCX — Windows Paintbrush | TIFF — Tagged Image File Format |
ICO — Icon File | PGM — Portable Graymap | XWD — X Window Dump |
BMP — Windows Bitmap
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | No Compression | RLE Compression | Output Class | Notes |
---|---|---|---|---|
1 bit | ✓ | – | logical | |
4 bit | ✓ | ✓ | uint8 | |
8 bit | ✓ | ✓ | uint8 | |
16 bit | ✓ | – | uint8 | 1 sample/pixel |
24 bit | ✓ | – | uint8 | 3 samples/pixel |
32 bit | ✓ | – | uint8 | 3 samples/pixel (1 byte padding) |
CUR — Cursor File
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | No Compression | Compression | Output Class |
---|---|---|---|
1 bit | ✓ | – | logical |
4 bit | ✓ | – | uint8 |
8 bit | ✓ | – | uint8 |
Note
By default, Microsoft® Windows® cursors are 32-by-32 pixels. Since MATLAB pointers must be 16-by-16, you might need to scale your image. You can use the imresize
function for this operation.
GIF — Graphics Interchange Format
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | No Compression | Compression | Output Class |
---|---|---|---|
1 bit | ✓ | – | logical |
2 bit to 8 bit | ✓ | – | uint8 |
HDF4 — Hierarchical Data Format
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | Raster Image with colormap | Rasterimage without colormap | Output Class | Notes |
---|---|---|---|---|
8 bit | ✓ | ✓ | uint8 | |
24 bit | – | ✓ | uint8 | 3 samples/pixel |
ICO — Icon File
See CUR — Cursor File
JPEG — Joint Photographic Experts Group
imread
reads any baseline JPEG image, aswell as JPEG images with some commonly used extensions. For informationon JPEG 2000 file support, see JPEG2000.
Supported Bits per Sample | LossyCompression | Lossless Compression | Output Class | Notes |
---|---|---|---|---|
8 bit | ✓ | ✓ | uint8 | Grayscale or RGB |
12 bit | ✓ | ✓ | uint16 | Grayscale or RGB |
16 bit | – | ✓ | uint16 | Grayscale |
JPEG 2000 — Joint Photographic Experts Group 2000
For information about JPEG files, see JPEG.
Note
Indexed JPEG 2000 images are not supported. Only JP2 compatiblecolor spaces are supported for JP2/JPX files. By default, all imagechannels are returned in the order they are stored in the file.
Supported Bits per Sample | Lossy Compression | LosslessCompression | Output Class | Notes |
---|---|---|---|---|
1 bit | ✓ | ✓ | logical | Grayscale only |
2 bit to 8 bit | ✓ | ✓ | uint8 or int8 | Grayscale or RGB |
9 bit to 16 bit | ✓ | ✓ | uint16 or int16 | Grayscale or RGB |
PBM — Portable Bitmap
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | Raw Binary | ASCII (Plain) Encoded | Output Class |
---|---|---|---|
1 bit | ✓ | ✓ | logical |
PCX — Windows Paintbrush
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | Output Class | Notes |
---|---|---|
1 bit | logical | Grayscale only |
8 bit | uint8 | Grayscale or indexed |
24 bit | uint8 | RGB Three 8-bit samples/pixel |
PGM — Portable Graymap
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | Raw Binary | ASCII (Plain) Encoded | Output Class | Notes |
---|---|---|---|---|
8 bit | ✓ | – | uint8 | |
16 bit | ✓ | – | uint16 | |
Arbitrary | – | ✓ | 1-bit to 8-bit: uint8 9-bitto 16-bit: uint16 | Values are scaled |
PNG — Portable Network Graphics
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | Output Class | Notes |
---|---|---|
1 bit | logical | Grayscale |
2 bit | uint8 | Grayscale |
4 bit | uint8 | Grayscale |
8 bit | uint8 | Grayscale or Indexed |
16 bit | uint16 | Grayscale or Indexed |
24 bit | uint8 | RGB Three 8-bit samples/pixel. |
48 bit | uint16 | RGB Three 16-bit samples/pixel. |
PPM — Portable Pixmap
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | Raw Binary | ASCII (Plain) Encoded | Output Class |
---|---|---|---|
Up to 16 bit | ✓ | – | uint8 |
Arbitrary | – | ✓ |
RAS — Sun Raster
This table lists supported bit depths and the data type of theoutput image data array.
Supported Bit Depths | Output Class | Notes |
---|---|---|
1 bit | logical | Bitmap |
8 bit | uint8 | Indexed |
24 bit | uint8 | RGB Three 8-bit samples/pixel |
32 bit | uint8 | RGB with Alpha Four 8-bit samples/pixel |
Aperio SVS — Aperio ScanScope Virtual Slide
TIFF-based image file format. imread
supports reading uncompressed and compressed images, including images with JPEG2000 compression. For more information, see TIFF — Tagged Image File Format.
TIFF — Tagged Image File Format
imread
reads most images supported by theTIFF specification or LibTIFF. The imread
functionsupports these TIFF capabilities:
Any number of samples per pixel
CCITT group 3 and 4 FAX, Packbits, JPEG, LZW, Deflate,ThunderScan compression, and uncompressed images
Logical, grayscale, indexed color, truecolor and hyperspectralimages
RGB, CMYK, CIELAB, ICCLAB color spaces. If the colorimage uses the CMYK color space,
A
is anm
-by-n
-by-4array. To determine which color space is used, useimfinfo
toget information about the graphics file and look at the value of thePhotometricInterpretation
field.If a file contains CIELAB color data,imread
convertsit to ICCLAB before bringing it into the MATLAB workspace. Thisconversion is necessary because 8-bit or 16-bit TIFF CIELAB-encodedvalues use a mixture of signed and unsigned data types that cannotbe represented as a single MATLAB array.Data organized into tiles or scanlines
imread
reads and converts TIFF images asfollows:
YCbCr images are converted into the RGB colorspace.
All grayscale images are read as if black =
0
,white = largest value.1-bit images are returned as class
logical
.16-bit floating-point images are returned as class
single
.CIELab images are converted into ICCLab colorspace.
XWD — X Window Dump
This table lists the supported bit depths, compression, andoutput classes for XWD files.
Supported Bit Depths | ZPixmaps | XYBitmaps | XYPixmaps | Output Class |
---|---|---|---|---|
1 bit | ✓ | – | ✓ | logical |
8 bit | ✓ | – | – | uint8 |
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
This function supports reading of 8-bit JPEG images only. The input argument
filename
must be a valid absolute path or relative path.This function generates code that uses a precompiled, platform-specific sharedlibrary (Image Processing Toolbox).
If you disable runtime error checking when generating your code and subsequently encounter a runtime error, the error is reported in one of these ways:
If
filename
is not a compile-time constant, an empty matrix is returned.If
filename
is a compile-time constant, a black image of the same dimensions asfilename
is returned.
GPU Code Generation
Generate CUDA® code for NVIDIA® GPUs using GPU Coder™.
Usage notes and limitations:
This function supports reading of 8-bit JPEG images only. The input argument
filename
must be a valid absolute path or relative path.This function generates code that uses a precompiled, platform-specific shared library (Image Processing Toolbox).
If you disable runtime error checking when generating your code and subsequently encounter a runtime error, the error is reported in one of these ways:
If
filename
is not a compile-time constant, an empty matrix is returned.If
filename
is a compile-time constant, a black image of the same dimensions asfilename
is returned.
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
Usage notes and limitations:
imread
does not support reading Hierarchical Data Format (HDF), SVS, or TIFF files when you runimread
in the background using backgroundPool or Parallel Computing Toolbox™Threadpool
.
For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
Introduced before R2006a
expand all
R2021b: Pixel differences in JPEG 2000 images
Pixel value differences might exist between JPEG 2000 images in R2021b and previous releases of MATLAB.
R2021a: Read only the first frame in a GIF file by default
When you read a GIF file without specifying additional arguments, the imread
function reads only the first frame by default. Previously, imread
read all the frames in the file by default.
R2020b: Read images from Aperio SVS and TIFF files containing JPEG 2000 compression
You can read Aperio SVS microscopy image files and TIFF image files with JPEG 2000 compression.
R2019b: Read images from multi-image PGM, PBM, or PPM files
You can read specified images from multi-image PGM, PBM, or PPM files.
See Also
Functions
- fread | image | imfinfo | imformats | imwrite | ind2rgb | tiffreadVolume (Image Processing Toolbox)
Live Editor Tasks
- Import Data
Topics
- Importing Images
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Deutsch
- English
- Français
- United Kingdom (English)
Contact your local office