Сохранение изображения opencv python

Сохранение изображения opencv python

Returns true if the specified image can be decoded by OpenCV.

Parameters

filename File name of the image

◆ haveImageWriter()

Returns true if an image with the specified filename can be encoded by OpenCV.

Parameters

filename File name of the image

◆ imcount()

Returns the number of images inside the give file.

The function imcount will return the number of pages in a multi-page image, or 1 for single-page images

Parameters

filename Name of file to be loaded.
flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR.

◆ imdecode() [1/2]

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.

◆ imdecodemulti()

bool cv::imdecodemulti ( InputArray buf,
int flags,
std::vector< Mat > & mats
)
Python:
cv.imdecodemulti( buf, flags[, mats] ) -> retval, mats

Reads a multi-page image from a buffer in memory.

The function imdecodemulti reads a multi-page image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns false.

See cv::imreadmulti 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.
mats A vector of Mat objects holding each page, if more than one.

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

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.
Читайте также:  Основы PHP

◆ 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)
  • AVIF — *.avif (see the Note section)
  • Portable image format — *.pbm, *.pgm, *.ppm *.pxm, *.pnm (always supported)
  • PFM files — *.pfm (see the Note section)
  • 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.
  • Use the IMREAD_UNCHANGED flag to keep the floating point values from PFM image.
  • By default number of pixels must be less than 2^30. Limit can be set using system variable OPENCV_IO_MAX_IMAGE_PIXELS

◆ imreadmulti() [1/2]

bool cv::imreadmulti ( const String & filename,
std::vector< Mat > & mats,
int flags = IMREAD_ANYCOLOR
)
Python:
cv.imreadmulti( filename[, mats[, flags]] ) -> retval, mats
cv.imreadmulti( filename, start, count[, 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.

Читайте также:  Mr. Camel

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

◆ imreadmulti() [2/2]

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

Loads a of images of a multi-page image from a file.

The function imreadmulti loads a specified range from 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.
start Start index of the image to load
count Count number of images to load
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:

    Источник

    Сохранение изображения с помощью cv2.imwrite() в OpenCV Python

    Чтобы сохранить изображение в локальное хранилище с помощью Python, используйте функцию cv2.imwrite() в библиотеке OpenCV.

    Синтаксис

    Где, path – это полный путь к выходному файлу, в который вы хотите записать массив numpy изображений.

    cv2.imwrite() возвращает логическое значение. true, если изображение успешно записано, и false, если изображение не было успешно записано по указанному локальному пути.

    Пример 1

    В этом примере мы прочитаем изображение, преобразуем его, а затем сохраним изображение в постоянном файловом хранилище с помощью метода imwrite().

    import cv2 #read image as grey scale img = cv2.imread('D:/image-1.png') #do some transformations on img #save matrix/array as image file isWritten = cv2.imwrite('D:/image-2.png', img) if isWritten: print('Image is successfully saved as file.')
    Image is successfully saved as file.

    Пример 2: со случайными значениями

    В этом примере мы напишем массив numpy как изображение, используя функцию cv2.imwrite(). Для этого мы создадим массив с тремя каналами для красного, зеленого и синего, содержащий случайные значения. В общих случаях мы читаем изображение, применяем некоторые преобразования к массиву и затем записываем изображение в локальное хранилище. Но в этом примере мы будем придерживаться массива со случайными значениями.

    import cv2 import numpy as np img = np.random.randint(255, size=(300, 600, 3)) isWritten = cv2.imwrite('D:/image-2.png', img) if isWritten: print('The image is successfully saved.')
    The image is successfully saved.

    Ниже приведено изображение, созданное со случайными значениями.

    Пример функции imwrite()

    В этом руководстве на примерах Python мы узнали, как использовать cv2.imwrite() для сохранения массива numpy в виде изображения.

    Источник

    Python OpenCV cv2.imwrite() – Save Image

    In our previous tutorial – cv2 imread(), we learned to read an image into a matrix. You may transform this matrix by using some algorithms. Then it may be required to save this matrix as an image.

    In this tutorial, we will learn how to save an array as image in file system.

    To save image to local storage using Python, use cv2.imwrite() function on OpenCV library.

    Syntax of cv2 imwrite()

    The syntax of imwrite() function is:

    where path is the complete path of the output file to which you would like to write the image numpy array.

    cv2.imwrite() returns a boolean value. True if the image is successfully written and False if the image is not written successfully to the local path specified.

    Examples

    1. Save matrix as image using cv2.imwrite()

    In this example, we will read an image, transform it and then save the image to persistent file storage using imwrite() method.

    Python Program

    import cv2 #read image as grey scale img = cv2.imread('D:/image-1.png') #do some transformations on img #save matrix/array as image file isWritten = cv2.imwrite('D:/image-2.png', img) if isWritten: print('Image is successfully saved as file.')
    Image is successfully saved as file.

    2. Save image created with random pixel values using cv2.imwrite()

    In this example, we will write a numpy array as image using cv2.imwrite() function. For that, we will create a numpy array with three channels for Red, Green and Blue containing random values.

    In general cases, we read image using cv2.imread(), apply some transformations on the array and then write the image to the local storage. But in this example, we will stick to the array with random values.

    Python Program

    import cv2 import numpy as np img = np.random.randint(255, size=(300, 600, 3)) isWritten = cv2.imwrite('D:/image-2.png', img) if isWritten: print('The image is successfully saved.')
    The image is successfully saved.

    Following is the image that is generated with the random values.

    Python OpenCV cv2 imwrite() Example

    Summary

    In this Python OpenCV Tutorial, we have seen how to use cv2.imwrite() to save numpy array as an image.

    Источник

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