opencv从文件中读取图片imread()函数以及Mat对象的复制方法

本文介绍了OpenCV中imread函数,它可从指定文件加载图像,若读取失败则返回空矩阵,还列出了支持的文件格式及注意事项。同时讲解了Mat对象的复制,包括clone和copyTo函数,它们实现深拷贝,而重载运算符‘=’是浅拷贝。

@brief Loads an image from a file.

@anchor imread

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

函数imread从指定的文件中加载一个图像并返回它。如果图像不能被读取(因为文件丢失、权限不当、不支持或无效格式),函数返回一个空矩阵(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)
-   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)

@note注意事项
-
   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.在彩色图像的情况下,解码后的图像将具有按** B G R **顺序存储的通道。
-   When using IMREAD_GRAYSCALE, the codec's internal grayscale conversion will be used, if available.Results may differ to the output of cvtColor()。使用IMREAD_GRAYSCALE时,将使用编解码器的内部灰度转换(如果可用)。结果可能与cvtColor()的输出有所不同

-   On Microsoft WindowsOS 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 @ref IMREAD_LOAD_GDAL to load the image,
    then the [GDAL](http://www.gdal.org) driver will be used in order to decode the image, supporting
    the following formats: [Raster](http://www.gdal.org/formats_list.html),
    [Vector](http://www.gdal.org/ogr_formats.html).
-   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 @ref IMREAD_IGNORE_ORIENTATION
    or @ref 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

@param filename Name of file to be loaded.
@param flags Flag that can take values of cv::ImreadModes
*/
CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR );

  • 返回值,Mat 类型, 即返回读取的图像,读取图像失败时返回一个空的矩阵对象(Mat::data == NULL)
  • 参数1 filename, 读取的图片文件名,可以使用相对路径或者绝对路径,但必须带完整的文件扩展名(图片格式后缀)
  • 参数2 flags, 一个读取标记,用于选择读取图片的方式,默认值为IMREAD_COLOR,flag值的设定与用什么颜色格式读取图片有关,传0是灰度图。
enum ImreadModes {
       IMREAD_UNCHANGED            = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). Ignore EXIF orientation.
       IMREAD_GRAYSCALE            = 0,  //!< If set, always convert image to the single channel grayscale image (codec internal conversion).
       IMREAD_COLOR                = 1,  //!< If set, always convert image to the 3 channel BGR color image.
       IMREAD_ANYDEPTH             = 2,  //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
       IMREAD_ANYCOLOR             = 4,  //!< If set, the image is read in any possible color format.
       IMREAD_LOAD_GDAL            = 8,  //!< If set, use the gdal driver for loading the image.
       IMREAD_REDUCED_GRAYSCALE_2  = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2.
       IMREAD_REDUCED_COLOR_2      = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2.
       IMREAD_REDUCED_GRAYSCALE_4  = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4.
       IMREAD_REDUCED_COLOR_4      = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4.
       IMREAD_REDUCED_GRAYSCALE_8  = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8.
       IMREAD_REDUCED_COLOR_8      = 65, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8.
       IMREAD_IGNORE_ORIENTATION   = 128 //!< If set, do not rotate the image according to EXIF's orientation flag.
     };
c++定义python定义说明
IMREAD_UNCHANGEDPython: cv.IMREAD_UNCHANGED如果设置,则按原样返回加载的图像(使用Alpha通道,否则会被裁剪)
IMREAD_GRAYSCALEPython: cv.IMREAD_GRAYSCALE如果设置,则始终将图像转换为单通道灰度图像(编解码器内部转换)。
IMREAD_COLORPython: cv.IMREAD_COLOR如果设置,请始终将图像转换为3通道BGR彩色图像。
IMREAD_ANYDEPTHPython: cv.IMREAD_ANYDEPTH如果设置,则在输入具有相应深度时返回16位/ 32位图像,否则将其转换为8位。
IMREAD_ANYCOLORPython: cv.IMREAD_ANYCOLOR如果设置,则以任何可能的颜色格式读取图像。
IMREAD_LOAD_GDALPython: cv.IMREAD_LOAD_GDAL如果设置,使用gdal驱动程序加载图像
IMREAD_REDUCED_GRAYSCALE_2Python: cv.IMREAD_REDUCED_GRAYSCALE_2如果设置,则始终将图像转换为单通道灰度图像,图像尺寸减小1/2。
IMREAD_REDUCED_COLOR_2Python: cv.IMREAD_REDUCED_COLOR_2如果设置,则始终将图像转换为3通道BGR彩色图像,图像尺寸减小1/2。
IMREAD_REDUCED_GRAYSCALE_4Python: cv.IMREAD_REDUCED_GRAYSCALE_4如果设置,则始终将图像转换为单通道灰度图像,图像尺寸减小1/4
IMREAD_REDUCED_COLOR_4Python: cv.IMREAD_REDUCED_COLOR_4如果设置,则始终将图像转换为3通道BGR彩色图像,图像尺寸减小1/4
IMREAD_REDUCED_GRAYSCALE_8Python: cv.IMREAD_REDUCED_GRAYSCALE_8如果设置,则始终将图像转换为单通道灰度图像,图像尺寸减小1/8。
IMREAD_REDUCED_COLOR_8Python: cv.IMREAD_REDUCED_COLOR_8如果设置,则始终将图像转换为3通道BGR彩色图像,图像尺寸减小1/8。
IMREAD_IGNORE_ORIENTATIONPython: cv.IMREAD_IGNORE_ORIENTATION如果设置,请不要根据EXIF的方向标志旋转图像。

 Mat对象的复制

函数原型

  • Mat clone() const;
  • void copyTo( OutputArray m ) const;
  • void copyTo( OutputArray m, InputArray mask) const;

copyTo()有重载,

inline Mat Mat::clone() const

{

   Mat m;
   copyTo(m);
   return m;
}

opencv矩阵赋值函数copyToclone重载元算赋‘=’之间实现的功能相似均是给不同的矩阵赋值功能。

copyTo和clone函数基本相同,被赋值的矩阵和赋值矩阵之间空间独立,不共享同一空间(深拷贝)。

但是重载元算赋‘=’,被赋值的矩阵和赋值矩阵之间空间共享,改变任一个矩阵的值,会同时影响到另一个矩阵(浅拷贝)。当矩阵作为函数的返回值时其功能和重载元算赋‘=’相同,赋值运算赋会给矩阵空间增加一次计数,所以函数变量返回后函数内部申请的变量空间并不会被撤销,在主函数中仍可以正常使用传递后的参数。

<think>好的,我现在需要回答用户关于如何使用C++和OpenCV从文件读取图片的问题。首先,我应该回顾用户提供的引用内容,特别是引用[1],因为里面有一个C++代码示例。让我仔细看一下引用[1]中的代码。 在引用[1]的代码中,用户展示了如何通过命令行参数读取图片路径,并使用cv::imread函数加载图像。具体来说,代码中的`auto img_path = argv[1];`获取了命令行参数,然后`cv::Mat img = cv::imread(img_path);`这一行读取了图像文件。此外,代码还检查了图像是否成功加载,如果失败则输出错误信息。这应该是一个关键点,需要包含在回答中。 用户可能需要一个完整的示例,而不仅仅是代码片段。因此,我应该提供一个简单的C++程序,包括必要的头文件、主函数结构、读取图像、错误处理以及显示和保存图像的部分。此外,用户可能对不同的参数和选项感兴趣,比如如何以灰度模式读取图像,或者如何处理不同的文件格式。 另外,用户提供的引用中还有其他相关内容,比如引用[3]和[4]提到了OpenCV在车牌识别和模型部署中的应用,这可能与图像处理的其他步骤相关,但当前问题主要关注读取图像,所以这些引用可能暂时用不上。不过,确保代码示例的准确性和完整性是重点。 需要确保代码中的语法正确,比如使用正确的命名空间、函数调用和错误检查。例如,在引用[1]的代码中,使用了`cv::imread`、`cv::imshow`和`cv::waitKey`等函数,这些都应该在示例中正确展示。同时,处理图像路径时,应该提到如何通过命令行参数传递路径,或者直接在代码中指定路径。 可能还需要解释一些关键函数的作用,比如cv::imread的不同参数,如cv::IMREAD_COLOR和cv::IMREAD_GRAYSCALE的区别,以及如何处理读取失败的情况。此外,保存图像使用cv::imwrite,这也是用户可能需要的部分,但主要问题在于读取,所以可能简要提及。 最后,根据用户的要求生成相关问题。这些问题应该围绕读取图像的扩展应用,比如错误处理、不同模式读取、性能优化或与其他OpenCV功能的结合。需要确保问题相关且有实际意义,帮助用户进一步学习。 总结一下,回答的结构应该是:先给出一个完整的代码示例,解释关键步骤,然后分点详细说明,最后生成相关问题。需要确保代码正确,语法符合OpenCV C++的标准,并且覆盖用户可能需要的各个方面。</think>以下是如何使用C++和OpenCV从文件读取图像的完整实现方法: ### 核心代码示例 ```cpp #include <opencv2/opencv.hpp> int main(int argc, char** argv) { // 检查输入参数 if (argc < 2) { std::cerr << "用法: " << argv[0] << " <图片路径>" << std::endl; return -1; } // 读取图像文件(支持JPG/PNG/BMP等格式) cv::Mat image = cv::imread(argv[1], cv::IMREAD_COLOR); // 验证读取结果 if (image.empty()) { std::cerr << "错误:无法读取图像 " << argv[1] << std::endl; return -1; } // 显示图像 cv::namedWindow("输入图像", cv::WINDOW_AUTOSIZE); cv::imshow("输入图像", image); cv::waitKey(0); return 0; } ``` ### 关键函数说明 1. **cv::imread()** - 第一个参数:字符串类型的文件路径 - 第二个参数(可选): - `cv::IMREAD_COLOR`:默认三通道BGR格式 - `cv::IMREAD_GRAYSCALE`:单通道灰度模式 - `cv::IMREAD_UNCHANGED`:保留Alpha通道 2. **错误处理** - 必须检查`cv::Mat.empty()`方法返回值 - 常见错误原因: - 文件路径错误 - 格式不支持(OpenCV支持超过20种图像格式[^1]) - 内存不足 3. **显示优化** - `cv::namedWindow()`可指定窗口属性 - `cv::waitKey(0)`保持窗口显示直到按键 ### 扩展应用 ```cpp // 读取灰度图像示例 cv::Mat gray_image = cv::imread("input.jpg", cv::IMREAD_GRAYSCALE); // 带Alpha通道读取 cv::Mat rgba_image = cv::imread("transparent.png", cv::IMREAD_UNCHANGED); // 批量读取示例 std::vector<cv::String> filenames; cv::glob("images/*.jpg", filenames); ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SOC罗三炮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值