Прочитать изображение из файла матлаб
A = imread( filename ) читает изображение из файла, заданного filename , выведение формата файла от его содержимого. Если filename мультифайл изображения, затем imread читает первое изображение в файле.
A = imread( filename , fmt ) дополнительно задает формат файла со стандартным расширением файла, обозначенным fmt . Если imread не может найти файл с именем заданным filename , это ищет файл с именем filename.fmt .
A = imread( ___ , idx ) читает заданное изображение или изображения от мультифайла изображения. Этот синтаксис применяется только к GIF, PGM, PBM, PPM, CUR, ICO, TIF и файлам HDF4. Необходимо задать filename введите, и можно опционально задать fmt .
A = imread( ___ , Name,Value ) задает параметры формата с помощью одного или нескольких аргументов пары "имя-значение", в дополнение к любому из входных параметров в предыдущих синтаксисах.
[ A , map ] = imread( ___ ) читает индексируемое изображение в filename в A и читает его связанную палитру в map . Значения палитры в файле изображения автоматически повторно масштабируются в область значений [0,1] .
[ A , map , transparency ] = imread( ___ ) дополнительно возвращает прозрачность изображения. Этот синтаксис применяется только к PNG, CUR и файлам ICO. Для файлов PNG, transparency альфа-канал, если вы присутствуете. Для CUR и файлов ICO, это - AND (непрозрачность) маска.
Примеры
Reading Image Data and Metadata from TIFF Files
While you can use imread to import image data and metadata from TIFF files, the function does have some limitations. For example, a TIFF file can contain multiple images and each images can have multiple subimages. While you can read all the images from a multi-image TIFF file with imread , you cannot access the subimages. Using the Tiff object, you can read image data, metadata, and subimages from 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.
A step-by-step example of using Tiff object methods and properties to read subimages from a TIFF file follows. To get the most out of the Tiff object, familiarize yourself with the TIFF specification and technical notes. See LibTIFF - TIFF Library and Utilities .
Reading Subimages from a TIFF File
A TIFF file can contain one or more image file directories (IFD). Each IFD contains image data and the metadata (tags) associated with the image. Each IFD can contain one or more subIFDs, which also can contain image data and metadata. These subimages are typically reduced-resolution (thumbnail) versions of the image data in the IFD containing the subIFDs.
To read the subimages in an IFD, you must get the location of the subimage from the SubIFD tag. The SubIFD tag contains an array of byte offsets that point to the subimages. You then can pass the address of the subIFD to the setSubDirectory method to make the subIFD the current IFD. Most Tiff object methods operate on the current IFD.
Open a TIFF file that contains images and subimages using the Tiff object constructor. This example uses the TIFF file created in Creating TIFF File Subdirectories, which contains one IFD directory with two subIFDs. The Tiff constructor opens the TIFF file, and makes the first subIFD in the file the current IFD:
Retrieve the locations of subIFDs associated with the current IFD. Use the getTag method to get the value of the SubIFD tag. This method returns an array of byte offsets that specify the location of subIFDs:
Navigate to the first subimage. First, set the currentIFD to the directory containing the first subimage:
Then, navigate to the first subIFD using the setSubDirectory method. Specify the byte offset of the subIFD as an argument. This call makes the subIFD the current IFD:
Read the image data from the current IFD (the first subIFD) the same way you read any other IFD in the file:
View the first subimage:
Navigate to the second subimage. First, reset the currentIFD to the directory containing the second subimage:
Then, navigate to the second subIFD using the setSubDirectory method. Specify the byte offset of the second subIFD:
Read the image data from the current IFD (the second subIFD) as you would with any other IFD in the file:
В его нативной форме изображение формата графических файлов не хранится как MATLAB ® матрица, или даже обязательно как матрица. Большинство графических файлов начинается с заголовка, содержащего специфичные для формата информационные теги, и продолжает растровые данные, которые могут быть считаны как непрерывный поток. Поэтому вы не можете использовать стандартные команды ввода-вывода MATLAB load и save считать и записать изображение формата графических файлов.
Вызовите специальные функции MATLAB, чтобы считать и записать данные изображения из форматов графических файлов:
Чтобы считать изображение формата графических файлов используют imread .
Чтобы записать изображение формата графических файлов, используйте imwrite .
Чтобы получить информацию о природе изображения формата графических файлов, используйте imfinfo .
Эта таблица дает более ясное изображение, которого команды MATLAB должны использоваться с который типы изображения.
Функции, чтобы использовать
Загрузите или сохраните матрицу как MAT-файл.
Загрузите или сохраните образ формата графических файлов, e.g., BMP, TIFF.
Отобразите любое изображение, загруженное в рабочее пространство MATLAB.
V79Compatible — Compatibility with MATLAB 7.9 (R2009b) and earlier
false (default) | true
Compatibility with MATLAB 7.9 (R2009b) and earlier, specified as the comma-separated pair consisting of 'V79Compatible' and either true or false . If you specify true , then the returned grayscale or RGB image is consistent with previous versions of imread (MATLAB 7.9 (R2009b) and earlier).
Example: 'V79Compatible',true
Data Types: logical
Запись графического изображения
Subsetting a Graphics Image (Cropping)
Sometimes you want to work with only a portion of an image file or you want to break it up into subsections. Specify the intrinsic coordinates of the rectangular subsection you want to work with and save it to a file from the command line. If you do not know the coordinates of the corner points of the subsection, choose them interactively, as the following example shows:
If you know what the image corner coordinates should be, you can manually define sp in the preceding example rather than using ginput .
You can also display a “rubber band box” as you interact with the image to subset it. See the code example for rbbox for details. For further information, see the documentation for the ginput and image functions.
Read Specific Image in Multipage TIFF File
Read the third image in the sample file, corn.tif .
Frames — Frame to read
1 (default) | positive integer | vector of integers | 'all'
Frames to read, specified as the comma-separated pair consisting of 'Frames' and a positive integer, a vector of integers, or 'all' . For example, if you specify the value 3, imread reads the third frame in the file. If you specify 'all' , then imread reads all frames and returns them in the order in which they appear in the file.
Example: 'frames',5
PixelRegion — Subimage to readcell array in the form
Subimage to read, specified as the comma-separated pair consisting of 'PixelRegion' and a cell array of the form . The rows input specifies the range of rows to read. The cols input specifies the range of columns to read. Both rows and cols must be two-element vectors containing 1-based indices. For example, 'PixelRegion', <[1 2],[3 4]>reads the subimage bounded by rows 1 and 2 and columns 3 and 4 in the image data. If the 'ReductionLevel' value is greater than 0, then rows and cols are coordinates of the subimage.
Example: 'PixelRegion',
Obtaining Information About Graphics Files
The imfinfo function enables you to obtain information about graphics files in any of the standard formats listed earlier. The information you obtain depends on the type of file, but it always includes at least the following:
Name of the file, including the folder path if the file is not in the current folder
To import data into the MATLAB ® workspace from a graphics file, use the imread function. Using this function, you can import data from files in many standard file formats, including the Tagged Image File Format (TIFF), Graphics Interchange Format (GIF), Joint Photographic Experts Group (JPEG), and Portable Network Graphics (PNG) formats. For a complete list of supported formats, see the imread reference page.
This example reads the image data stored in a file in JPEG format into the MATLAB workspace as the array I :
imread represents the image in the workspace as a multidimensional array of class uint8 . The dimensions of the array depend on the format of the data. For example, imread uses three dimensions to represent RGB color images:
For more control over reading TIFF files, use the Tiff object—see Reading Image Data and Metadata from TIFF Files for more information.
'V79Compatible' — Совместимость с MATLAB 7.9 (R2009b) и ранее
false (значение по умолчанию) | true
Совместимость с MATLAB 7.9 (R2009b) и ранее, заданный как разделенная запятой пара, состоящая из 'V79Compatible' и любой true или false . Если вы задаете true , затем возвращенное изображение шкалы полутонов или RGB сопоставимо с предыдущими версиями imread (MATLAB 7.9 (R2009b) и ранее).
Пример: 'V79Compatible',true
Типы данных: логический
Файлы PNG
BackgroundColor — Background color
'none' | integer | 3-element vector of integers
Background color, specified as 'none' , an integer, or a three-element vector of integers. If BackgroundColor is 'none' , then imread does not perform any compositing. Otherwise, imread blends transparent pixels with the background color.
If the input image is indexed, then the value of BackgroundColor must be an integer in the range [1,P] , where P is the colormap length.
If the input image is grayscale, then the value of BackgroundColor must be an integer in the range [0,1] .
If the input image is RGB, then the value of BackgroundColor must be a three-element vector with values in the range [0,1] .
The default value for BackgroundColor depends on the presence of the transparency output argument and the image type:
If you request the transparency output argument, then the default value of BackgroundColor is 'none' .
If you do not request the transparency output and the PNG file contains a background color chunk, then that color is the default value for BackgroundColor .
If you do not request the transparency output and the file does not contain a background color chunk, then the default value for BackgroundColor is 1 for indexed images, 0 for grayscale images, and [0 0 0] for truecolor (RGB) images.
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-image GIF, CUR, ICO, and HDF4 files.
When reading multiple frames from the same GIF file, specify idx as a vector of frames or use the 'Frames','all' name-value pair argument. Because of the way that GIF files are structured, these syntaxes provide faster performance compared to calling imread in a loop.
For HDF4 files, idx corresponds to the reference number of the image to read. Reference numbers do not necessarily correspond to the order of the images in the file. You can use imfinfo to match image order with reference number.
Example: 3
Data Types: double
'Info' — Информация об изображении
массив структур
Информация об изображении, заданном как разделенная запятой пара, состоящая из 'Info' и массив структур, возвращенный imfinfo функция. Используйте Info аргумент пары "имя-значение", чтобы помочь imread найдите изображения в файле TIFF мультиизображений более быстро.
Типы данных: struct
'BackgroundColor' BackgroundColor
'none' | целое число | вектор с 3 элементами целых чисел
Цвет фона, заданный как 'none' , целое число или трехэлементный вектор целых чисел. Если BackgroundColor 'none' , затем imread не выполняет составления композита. В противном случае, imread прозрачные пиксели смешений с цветом фона.
Если входное изображение индексируется, то значение BackgroundColor должно быть целое число в области значений [1,P] , где P длина палитры.
Если входное изображение является шкалой полутонов, то значение BackgroundColor должно быть целое число в области значений [0,1] .
Если входное изображение является RGB, то значение BackgroundColor должен быть трехэлементный вектор со значениями в области значений [0,1] .
Значение по умолчанию для BackgroundColor зависит от присутствия transparency выходной аргумент и тип изображения:
Если вы запрашиваете transparency выходной аргумент, затем значение по умолчанию BackgroundColor 'none' .
Если вы не запрашиваете transparency выведите и файл PNG содержит фрагмент цвета фона, затем тот цвет является значением по умолчанию для BackgroundColor .
Если вы не запрашиваете transparency выведите и файл не содержит фрагмент цвета фона, затем значение по умолчанию для BackgroundColor 1 для индексируемых изображений, 0 для полутоновых изображений и [0 0 0] для истинного цвета (RGB) изображения.
Файлы TIFF
Чтение определенного изображения в многостраничном файле TIFF
Считайте третье изображение в файле примера, corn.tif .
Index — Image to read
1 (default) | positive integer
Image to read, specified as the comma-separated pair consisting of 'Index' and a positive integer. For example, if the value of Index is 3, then imread reads the third image in the file.
Data Types: single | double
Чтение и изображение на дисплее
Считайте демонстрационное изображение.
imread возвращает 650 600 3 массивами, A .
Возвратите альфа-канал изображения PNG
Возвратите альфа-канал демонстрационного изображения, peppers.jpg .
Никакой альфа-канал не присутствует, таким образом , alpha isempty.
Input Arguments
idx — Отобразите, чтобы читать
целочисленный скаляр | вектор целых чисел
Отобразите, чтобы читать, заданный как целочисленный скаляр или, для файлов GIF, вектора целых чисел. Например, если idx 3, затем imread возвращает третье изображение в файле. Для файла GIF, если idx 1:5 , затем imread возвращает только первые пять систем координат. idx аргумент поддерживается только для GIF мультиизображений, CUR, ICO и файлов HDF4.
При чтении нескольких систем координат из того же файла GIF задайте idx как вектор систем координат или использования 'Frames','all' аргумент пары "имя-значение". Из-за способа, которым структурированы файлы GIF, эти синтаксисы обеспечивают более быструю производительность по сравнению с вызовом imread в цикле.
Для файлов HDF4, idx соответствует ссылочному номеру изображения, чтобы читать. Ссылочные номера не обязательно соответствуют порядку изображений в файле. Можно использовать imfinfo совпадать с порядком изображений ссылочному номеру.
Пример 3
Типы данных: double
Read Specified Region of TIFF Image
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.
imread reads the image data in rows 1-2 and columns 2-5 from corn.tif and returns the 2-by-4 array, A .
'Index' — Отобразите, чтобы читать
1 (значение по умолчанию) | положительное целое число
Отобразите, чтобы читать, заданный как разделенная запятой пара, состоящая из 'Index' и положительное целое число. Например, если значение Index 3, затем imread читает третье изображение в файле.
Типы данных: single | double
Чтение заданной области изображения TIFF
Считайте определенную область пикселей демонстрационного изображения, corn.tif .
Задайте 'PixelRegion' параметр с массивом ячеек векторов, указывающих на контуры области, чтобы читать. Первый вектор указывает диапазон строк, чтобы читать, и второй вектор указывает диапазон столбцов, чтобы читать.
imread читает данные изображения в строках 1-2 и столбцах 2-5 от corn.tif и возвращается 2 4 массив, A .
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 of a TIFF file.
ReductionLevel — Reduction of image resolution
0 (default) | nonnegative integer
Reduction of the image resolution, specified as the comma-separated pair consisting of 'ReductionLevel' and a nonnegative integer. For reduction level L, the image resolution is reduced by a factor of 2^L. The reduction level is limited by the total number of decomposition levels as specified by the 'WaveletDecompositionLevels' field in the output of the imfinfo function.
Example: 'ReductionLevel',5
Data Types: single | double
'Frames' — Структурируйте, чтобы читать
1 (значение по умолчанию) | положительное целое число | вектор целых чисел | 'all'
Системы координат, чтобы читать, заданный как разделенная запятой пара, состоящая из 'Frames' и положительное целое число, вектор целых чисел или 'all' . Например, если вы задаете значение 3, imread читает третью систему координат в файле. Если вы задаете 'all' , затем imread чтения все системы координат и возвращают их в порядке, в котором они появляются в файле.
Пример: 'frames',5
JPEG 2 000 файлов
'PixelRegion' — Подотобразите, чтобы читатьмассив ячеек в форме
Подотобразите, чтобы читать, заданный как разделенная запятой пара, состоящая из 'PixelRegion' и массив ячеек формы . rows введите указывает диапазон строк, чтобы читать. cols введите указывает диапазон столбцов, чтобы читать. Оба rows и cols должны быть двухэлементные векторы, содержащие индексы на основе 1. Например, 'PixelRegion', <[1 2],[3 4]>читает подызображение, ограниченное строками 1 и 2 и столбцами 3 и 4 в данных изображения. Если 'ReductionLevel' значение больше 0, затем rows и cols координаты подызображения.
Пример: 'PixelRegion',
filename — Имя графического файла
вектор символов | представляет скаляр в виде строки
Имя графического файла, заданного как вектор символов или скаляр строки.
В зависимости от местоположения вашего файла, filename может взять одну из следующих форм.
Задайте имя файла в filename .
Пример: 'myImage.jpg'
Если файл не находится в текущей папке или в папке на пути MATLAB, то задайте полное имя или относительный путь.
Пример: 'C:\myFolder\myImage.ext'
Пример: '\imgDir\myImage.ext'
Если файл хранится в удаленном местоположении, то filename должен содержать полный путь файла, заданного как универсальный локатор ресурса (URL) формы:
scheme_name :// path_to_file / my_file.ext
На основе вашего удаленного местоположения, scheme_name может быть одно из значений в этой таблице.
Удаленное местоположение | scheme_name |
---|---|
Amazon S3™ | s3 |
Устройство хранения данных Windows Azure ® Blob | wasb , wasbs |
HDFS™ | hdfs |
Для получения дополнительной информации смотрите работу с Удаленными данными.
Пример: 's3://bucketname/path_to_file/my_image.jpg'
Для получения информации о битовых глубинах схемы сжатия и цветовые пространства, поддержанные для каждого типа файла, видят Алгоритмы.
Типы данных: char | string
Подмножество графическое изображение (обрезка)
Иногда вы хотите работать только с фрагментом файла изображения, или вы хотите разбить его в подразделы. Задайте внутренние координаты прямоугольного подраздела, с которым вы хотите работать и сохранить его в файл из командной строки. Если вы не знаете координаты угловых точек подраздела, выбираете их в интерактивном режиме, когда следующий пример показывает:
Если вы знаете, каковы угловые координаты изображений должны быть, можно вручную задать sp в предыдущем примере вместо того, чтобы использовать ginput .
Можно также отобразить “поле круглой резинки”, когда вы взаимодействуете с изображением к подмножеству оно. Смотрите пример кода для rbbox для деталей. Для получения дополнительной информации см. документацию для ginput и image функции.
Получение информации о графических файлах
imfinfo функция позволяет вам получить информацию о графических файлах в любом из стандартных форматов, перечисленных ранее. Информация, которую вы получаете, зависит от типа файла, но это всегда включает, по крайней мере, следующее:
Имя файла, включая путь к папке, если файл не находится в текущей папке
Номер версии формата файла
Дата модификации файла
Размер файла в байтах
Ширина изображения в пикселях
Высота изображения в пикселях
Количество бит на пиксель
Тип изображения: RGB (истинный цвет), интенсивность (шкала полутонов), или индексированный
A = imread( filename ) reads the image from the file specified by filename , inferring the format of the file from its contents. If filename is a multi-image file, then imread reads the first image in the file.
A = imread( filename , fmt ) additionally specifies the format of the file with the standard file extension indicated by fmt . If imread cannot find 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 .
A = imread( ___ , Name,Value ) specifies format-specific options using one or more name-value pair arguments, in addition to any of the input arguments in the previous syntaxes.
[ A , map ] = imread( ___ ) reads the indexed image in filename into A and reads its associated colormap into map . Colormap values in the image file are automatically rescaled into the range [0,1] .
[ A , map , transparency ] = imread( ___ ) additionally returns the image transparency. 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.
'PixelRegion' — Контур области
cellArray
Контур области, заданный как разделенная запятой пара, состоящая из 'PixelRegion' и массив ячеек формы . rows введите указывает диапазон строк, чтобы читать. cols введите указывает диапазон столбцов, чтобы читать. rows и cols должны быть или двухэлементные или трехэлементные векторы индексов на основе 1. Двухэлементный вектор задает первые и последние строки или столбцы, чтобы читать. Например, 'PixelRegion', <[1 2],[3 4]>читает область, ограниченную строками 1 и 2 и столбцами 3 и 4 в данных изображения.
Трехэлементный вектор должен быть в форме [start increment stop] , где start первая строка или столбец, чтобы читать, increment инкрементное значение и stop последняя строка или столбец, чтобы читать. Этот синтаксис позволяет субдискретизацию изображений. Например, 'PixelRegion', <[1 2 10],[4 3 12]>читает область, ограниченную строками 1 и 10 и столбцами 4 и 12 и демонстрационными данными из каждых 2 пикселей в вертикальном направлении и каждых 3 пикселей в горизонтальном направлении.
In its native form, a graphics file format image is not stored as a MATLAB ® matrix, or even necessarily as a matrix. Most graphics files begin with a header containing format-specific information tags, and continue with bitmap data that can be read as a continuous stream. For this reason, you cannot use the standard MATLAB I/O commands load and save to read and write a graphics file format image.
Call special MATLAB functions to read and write image data from graphics file formats:
To read a graphics file format image use imread .
To write a graphics file format image, use imwrite .
To obtain information about the nature of a graphics file format image, use imfinfo .
This table gives a clearer picture of which MATLAB commands should be used with which image types.
Functions to Use
Load or save a matrix as a MAT-file.
Load or save graphics file format image, e.g., BMP, TIFF.
Display any image loaded into the MATLAB workspace.
fmt 'imageFormat'
вектор символов | представляет скаляр в виде строки
Формат изображения, заданный как вектор символов или скаляр строки указание на стандартное расширение файла. Вызовите imformats видеть список поддерживаемых форматов и их расширений файла.
Пример: 'png'
Типы данных: char | string
Reading a Graphics Image
Note
For indexed images, imread always reads the colormap into an array of class double , even though the image array itself can be of class uint8 or uint16 .
The following commands read the image ngc6543a.jpg into the workspace variable RGB and then displays the image using the image function:
You can write (save) image data using the imwrite function. The statements
create a BMP file containing the clown image.
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.
Specify the name of the file in filename .
Example: 'myImage.jpg'
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: 'C:\myFolder\myImage.ext'
Example: '\imgDir\myImage.ext'
If the file is stored at a remote location, then filename must contain the full path of the file specified as a uniform resource locator (URL) of the form:
scheme_name :// path_to_file / my_file.ext
Based on the remote location, scheme_name can be one of the values in this table.
Remote Location | scheme_name |
---|---|
Amazon S3™ | s3 |
Windows Azure ® Blob Storage | wasb , wasbs |
HDFS™ | hdfs |
For more information, see Work with Remote Data.
Example: 's3://bucketname/path_to_file/my_image.jpg'
For information on the bit depths, compression schemes, and color spaces supported for each file type, see Algorithms.
Data Types: char | string
Return Alpha Channel of PNG Image
Return the alpha channel of the sample image, peppers.jpg .
No alpha channel is present, so alpha is empty.
Аргументы в виде пар имя-значение
Задайте дополнительные разделенные запятой пары Name,Value аргументы. Name имя аргумента и Value соответствующее значение. Name должен появиться в кавычках. Вы можете задать несколько аргументов в виде пар имен и значений в любом порядке, например: Name1, Value1, . NameN, ValueN .
Пример: 'Index',5 читает пятое изображение файла TIFF.
Файлы GIF
Examples
'ReductionLevel' — Сокращение разрешения изображения
0 (значений по умолчанию) | неотрицательное целое число
Сокращение разрешения изображения, заданного как разделенная запятой пара, состоящая из 'ReductionLevel' и неотрицательное целое число. Для уровня сокращения L разрешение изображения уменьшается фактором 2^L. Уровень сокращения ограничивается общим количеством уровней разложения, как задано the 'WaveletDecompositionLevels' поле в выходе imfinfo функция.
Пример: 'ReductionLevel',5
Типы данных: single | double
Convert Indexed Image to RGB
Read the first image in the sample indexed image file, 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.
Convert the indexed image to an RGB image. The result is a 415-by-312-by-3 array of type double .
Check that values of the RGB image are in the range [0, 1].
Read and Display Image
Read a sample image.
imread returns a 650-by-600-by-3 array, A .
Display the image.
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
Преобразуйте индексируемое изображение в RGB
Читайте первое изображение в выборке индексировало файл изображения, corn.tif .
Индексируемое изображение X 415 312 массив типа uint8 . Палитра cmap 256 3 матрица типа double , поэтому существуют 256, раскрашивает индексируемое изображение. Отобразите изображение.
Преобразуйте индексируемое изображение в изображение RGB. Результатом являются 415 312 3 массивами типа double .
Проверяйте, что значения изображения RGB находятся в области значений [0, 1].
Info — Information about image
structure array
Information about the image, specified as the comma-separated pair consisting of 'Info' and a structure array returned by the imfinfo function. Use the Info name-value pair argument to help imread locate the images in a multi-image TIFF file more quickly.
Data Types: struct
PixelRegion — Region boundary
cell array
Region boundary, specified as the comma-separated pair consisting of 'PixelRegion' and a cell array of the form . The rows input specifies the range of rows to read. The cols input specifies the range of columns to read. rows and cols must be either two-element or three-element vectors of 1-based indices. A two-element vector specifies the first and last rows or columns to read. For example, 'PixelRegion', <[1 2],[3 4]>reads the region bounded by rows 1 and 2 and columns 3 and 4 in the image data.
A three-element vector must be in the form [start increment stop] , where start is the first row or column to read, increment is an incremental value, and stop is the last row or column to read. This syntax allows image downsampling. For example, 'PixelRegion', <[1 2 10],[4 3 12]>reads the region bounded by rows 1 and 10 and columns 4 and 12, and samples data from every 2 pixels in the vertical direction, and every 3 pixels in the horizontal direction.
Чтение графического изображения
Примечание
Для индексируемых изображений, imread всегда читает палитру в массив класса double , даже при том, что сама матрица изображений может иметь класс uint8 или uint16 .
Следующие команды читают изображение ngc6543a.jpg в переменную RGB рабочей области и затем отображает изображение с помощью image функция:
Можно записать (сохраняют) данные изображения с помощью imwrite функция. Операторы
создайте файл BMP, содержащий изображение клоуна.
Getting Information About Image Files
If you have a file in a standard graphics format, use the imfinfo function to get information about its contents. The imfinfo function returns a structure containing information about the file. The fields in the structure vary with the file format, but imfinfo always returns some basic information including the file name, last modification date, file size, and format.
This example returns information about a file in Joint Photographic Experts Group (JPEG) format:
Writing a Graphics Image
Читайте также: