Python opencv cv2 imread

Python opencv cv2 imread

Reads an image from a buffer in memory.

The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns an empty matrix ( Mat::data==NULL ).

See cv::imread for the list of supported formats and flags description.

Note In the case of color images, the decoded images will have the channels stored in B G R order. Parameters

buf Input array or vector of bytes.
flags The same flags as in cv::imread, see cv::ImreadModes.

◆ imdecode() [2/2]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters

buf
flags
dst The optional output placeholder for the decoded matrix. It can save the image reallocations when the function is called repeatedly for images of the same size.

◆ imencode()

bool cv::imencode ( const String & ext,
InputArray img,
std::vector< uchar > & buf,
const std::vector < int >& params = std::vector< int >()
)
Python:
cv.imencode( ext, img[, params] ) -> retval, buf

Encodes an image into a memory buffer.

The function imencode compresses the image and stores it in the memory buffer that is resized to fit the result. See cv::imwrite for the list of supported formats and flags description.

Читайте также:  Язык программирования java коротко

Parameters

ext File extension that defines the output format. Must include a leading period.
img Image to be written.
buf Output buffer resized to fit the compressed image.
params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags.

◆ imread()

Loads an image from a file.

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).

Currently, the following file formats are supported:

  • Windows bitmaps — *.bmp, *.dib (always supported)
  • JPEG files — *.jpeg, *.jpg, *.jpe (see the Note section)
  • JPEG 2000 files — *.jp2 (see the Note section)
  • Portable Network Graphics — *.png (see the Note section)
  • WebP — *.webp (see the Note section)
  • Portable image format — *.pbm, *.pgm, *.ppm *.pxm, *.pnm (always supported)
  • Sun rasters — *.sr, *.ras (always supported)
  • TIFF files — *.tiff, *.tif (see the Note section)
  • OpenEXR Image files — *.exr (see the Note section)
  • Radiance HDR — *.hdr, *.pic (always supported)
  • Raster and Vector geospatial data supported by GDAL (see the Note section)
  • The function determines the type of an image by the content, not by the file extension.
  • In the case of color images, the decoded images will have the channels stored in B G R order.
  • When using IMREAD_GRAYSCALE, the codec’s internal grayscale conversion will be used, if available. Results may differ to the output of cvtColor()
  • On Microsoft Windows* OS and MacOSX*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware that currently these native image loaders give images with different pixel values because of the color management embedded into MacOSX.
  • On Linux*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, «libjpeg-dev», in Debian* and Ubuntu*) to get the codec support or turn on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake.
  • In the case you set WITH_GDAL flag to true in CMake and IMREAD_LOAD_GDAL to load the image, then the GDAL driver will be used in order to decode the image, supporting the following formats: Raster, Vector.
  • If EXIF information is embedded in the image file, the EXIF orientation will be taken into account and thus the image will be rotated accordingly except if the flags IMREAD_IGNORE_ORIENTATION or IMREAD_UNCHANGED are passed.
  • By default number of pixels must be less than 2^30. Limit can be set using system variable OPENCV_IO_MAX_IMAGE_PIXELS

◆ imreadmulti()

bool cv::imreadmulti ( const String & filename,
std::vector< Mat > & mats,
int flags = IMREAD_ANYCOLOR
)
Python:
cv.imreadmulti( filename[, mats[, flags]] ) -> retval, mats

Loads a multi-page image from a file.

The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects.

Parameters

filename Name of file to be loaded.
mats A vector of Mat objects holding each page.
flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR.

See also cv::imread

◆ imwrite()

bool cv::imwrite ( const String & filename,
InputArray img,
const std::vector < int >& params = std::vector< int >()
)
Python:
cv.imwrite( filename, img[, params] ) -> retval

Saves an image to a specified file.

The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see cv::imread for the list of extensions). In general, only 8-bit unsigned (CV_8U) single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function, with these exceptions:

  • With OpenEXR encoder, only 32-bit float (CV_32F) images can be saved.
    • 8-bit unsigned (CV_8U) images are not supported.
    • All images will be converted to 32-bit float (CV_32F).
    • PNG images with an alpha channel can be saved using this function. To do this, create 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535 (see the code sample below).
    • Multiple images (vector of Mat) can be saved in TIFF format (see the code sample below).
    • 32-bit float 3-channel (CV_32FC3) TIFF images will be saved using the LogLuv high dynamic range encoding (4 bytes per pixel)

    If the image format is not supported, the image will be converted to 8-bit unsigned (CV_8U) and saved that way.

    If the format, depth or channel order is different, use Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O functions to save the image to XML or YAML format.

    The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file. It also demonstrates how to save multiple images in a TIFF file:

    Источник

    Python OpenCV Read Image – cv2 imread()

    You can read image into a numpy array using opencv library. The array contains pixel level data. And as per the requirement, you may modify the data of the image at a pixel level by updating the array values.

    To read an image in Python using OpenCV, use cv2.imread() function. imread() returns a 2D or 3D matrix based on the number of color channels present in the image. For a binary or grey scale image, 2D array is sufficient. But for a colored image, you need 3D array.

    In this tutorial, we shall learn in detail how to read an image using OpenCV, by considering some of the regular scenarios.

    We will also learn the order in which imread() function decodes the color channels from an image and how imread() treats different image extensions.

    Syntax of cv2.imread()

    The syntax of cv2.imread() function is given below.

    cv2.imread(/path/to/image, flag)

    where /path/to/image has to be the complete absolute path to the image. The flag is optional and one of the following possible values can be passed for the flag.

    • cv2.IMREAD_COLOR reads the image with RGB colors but no transparency channel. This is the default value for the flag when no value is provided as the second argument for cv2.imread().
    • cv2.IMREAD_GRAYSCALE reads the image as grey image. If the source image is color image, grey value of each pixel is calculated by taking the average of color channels, and is read into the array.
    • cv2.IMREAD_UNCHANGED reads the image as is from the source. If the source image is an RGB, it loads the image into array with Red, Green and Blue channels. If the source image is ARGB, it loads the image with three color components along with the alpha or transparency channel.

    Examples

    1. Read color image using imread()

    In this example, we will read a color image. As the default value of the flag argument is cv2.IMREAD_COLOR, we are not passing the flag explicitly.

    Python Program

    import cv2 #read image img = cv2.imread('D:/image-1.png') #print its shape print('Image Dimensions :', img.shape)

    Run the above python program, and you shall get the following output.

    Image Dimensions : (400, 640, 3)

    img.shape returns tuple representing (height, width, number_of_channels). Height of the image is 400 pixels, width is 640 and there are three color channels in the image. For cv2.IMREAD_COLOR, transparency channel is ignored even if present.

    2. OpenCV cv2 – Read image as greyscale

    In this example, we will read image as a grey scale image. Input can be color image or grey scale image. But, if flag argument is cv2.IMREAD_GRAYSCALE, the image is read as grey scale image.

    Python Program

    import cv2 img = cv2.imread('D:/image-1.png', cv2.IMREAD_GRAYSCALE) print('Image Dimensions :', img.shape)
    Image Dimensions : (400, 640)

    Height of the image is 400 pixels, width is 640. Each element in the array represents grey scale value at the respective pixel.

    3. OpenCV cv2 – Read image with transparency channel

    In this example, we will read an image with transparency channel. If there is a transparency channel in the image, then we can pass cv2.IMREAD_UNCHANGED to read the transparency channel along with the color channels.

    Python Program

    import cv2 img = cv2.imread('D:/image-1.png', cv2.IMREAD_UNCHANGED) print('Image Dimensions :', img.shape)
    Image Dimensions : (400, 640, 4)

    We have read all the four channels of the image. Namely Red, Green, Blue and Transparency.

    imread() and Color Channels

    imread() decodes the image into a matrix with the color channels stored in the order of Blue, Green, Red and A (Transparency) respectively.

    If (400, 640, 4) is the shape of the image, then

    • (:, :, 0) represents Blue channel
    • (:, :, 1) represents Green channel
    • (:, :, 2) represents Red channel
    • (:, :, 3) represents Transparency channel

    imread() and File Extensions

    There are many extensions used for images based on the operating system, compression technique, etc.

    When imread() method reads image, it does not consider the extension of the image file name to determine the format of the image. But decides the extension based on the format present in the file data.

    imread() supports JPEGs, PNGs, and TIFFs across all platforms. But for the combination of other formats and Operating Systems, imread() may consider the operating system level codecs. You may refer the official documentation of imread() for these special scenarios.

    Summary

    In this Python OpenCV Tutorial, we learned how to use cv2.imread() method to read an image into a Python Array.

    Источник

Оцените статью