OpenCV2的学习就从imread 和 imwrite函数开始

加载图片Loads an image from a file.

C++:Mat imread(const string& filename, int flags=1 )
Python:cv2.imread(filename[, flags]) → retval
C:IplImage* cvLoadImage(const char* filename, int iscolor=CV_LOAD_IMAGE_COLOR )
C:CvMat* cvLoadImageM(const char* filename, int iscolor=CV_LOAD_IMAGE_COLOR )
Python:cv.LoadImage(filename, iscolor=CV_LOAD_IMAGE_COLOR) → None
Python:cv.LoadImageM(filename, iscolor=CV_LOAD_IMAGE_COLOR) → None
imread 函数第二各参数默认情况下读取彩色图片。
Parameters:
  • filename – Name of file to be loaded.
  • flags –

    Flags specifying the color type of a loaded image:

    • CV_LOAD_IMAGE_ANYDEPTH - If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
    • CV_LOAD_IMAGE_COLOR - If set, always convert image to the color one
    • CV_LOAD_IMAGE_GRAYSCALE - If set, always convert image to the grayscale one
    • CV_LOAD_IMAGE_UNCHANGED -1 原始图像

      CV_LOAD_IMAGE_GRAYSCALE 0 灰度图像

      CV_LOAD_IMAGE_COLOR 1 彩色

      CV_LOAD_IMAGE_ANYDEPTH 2 任何彩度

      CV_LOAD_IMAGE_ANYCOLOR 4 任何彩色

    • >0 Return a 3-channel color image.

      Note

      In the current implementation the alpha channel, if any, is stripped from the output image. Use negative value if you need the alpha channel.

    • =0 Return a grayscale image.
    • <0 Return the loaded image as is (with alpha channel).

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 Notes section)
  • JPEG 2000 files - *.jp2 (see the Notes section)
  • Portable Network Graphics - *.png (see the Notes section)
  • Portable image format - *.pbm, *.pgm, *.ppm (always supported)
  • Sun rasters - *.sr, *.ras (always supported)
  • TIFF files - *.tiff, *.tif (see the Notes section)

Note

  • The function determines the type of an image by the content, not by the file extension.
  • 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.

Note

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

注意 彩色图片的存储顺序是 蓝 绿 红

imwrite

Saves an image to a specified file.

C++:bool imwrite(const string& filename, InputArray img, const vector<int>& params=vector<int>() )
Python:cv2.imwrite(filename, img[, params]) → retval
C:int cvSaveImage(const char* filename, const CvArr* image, const int* params=0 )
Python:cv.SaveImage(filename, image) → None
Parameters:
  • filename – Name of the file.
  • image – Image to be saved.
  • params –

    Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, ... . The following parameters are currently supported:

    • For JPEG, it can be a quality ( CV_IMWRITE_JPEG_QUALITY ) from 0 to 100 (the higher is the better). Default value is 95.
    • For PNG, it can be the compression level ( CV_IMWRITE_PNG_COMPRESSION ) from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3.
    • For PPM, PGM, or PBM, it can be a binary format flag ( CV_IMWRITE_PXM_BINARY ), 0 or 1. Default value is 1.

The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see imread()for the list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use Mat::convertTo() , and cvtColor() to convert it before saving. Or, use the universal FileStorage I/O functions to save the image to XML or YAML format.

It is possible to store PNG images with an alpha channel 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. The sample below shows how to create such a BGRA image and store to PNG file. It also demonstrates how to set custom compression parameters

#include <vector>
#include <stdio.h>
#include <opencv2/opencv.hpp>using namespace cv;
using namespace std;void createAlphaMat(Mat &mat)
{CV_Assert(mat.channels() == 4);for (int i = 0; i < mat.rows; ++i) {for (int j = 0; j < mat.cols; ++j) {Vec4b& bgra = mat.at<Vec4b>(i, j);bgra[0] = UCHAR_MAX; // Bluebgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Greenbgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Redbgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha}}
}int main(int argv, char **argc)
{// Create mat with alpha channelMat mat(480, 640, CV_8UC4);createAlphaMat(mat);vector<int> compression_params;compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);compression_params.push_back(9);try {imwrite("alpha.png", mat, compression_params);}catch (runtime_error& ex) {fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what());return 1;}fprintf(stdout, "Saved PNG file with alpha data.\n");return 0;
}

OpenCV2:imread 和 imwrite相关推荐

  1. OpenCV-Python教程:读取图像、显示、写入图像(imread,imshow,imwrite,waitKey)

    原文链接:http://www.juzicode.com/archives/5395 返回Opencv-Python教程 这篇文件介绍怎么用OpenCV-Python从静态图片文件中获取图像.显示图像 ...

  2. imread、imwrite、imfinfo、fread、imshow

    一.imread直接读取图片数据. 示例一 下面这段代码读取一张图片并显示出来 filename = 'e. bmp'; imgRgb = imread(filename); % 读入一幅彩色图像 i ...

  3. imread函数 matlab_【MATLAB图像处理学习】1.读取和显示图片

    CHAPTER2 图像处理的基础函数 [使用的教材:冈萨雷斯 数字图像处理MATLAB(Digital image processing with Matlab] [原书图片下载地址:点这里] 先介绍 ...

  4. OpenCV学习笔记(六)(七)(八)(九)(十)

    OpenCV学习笔记(六)--对XML和YAML文件实现I/O操作 1. XML.YAML文件的打开和关闭 XML\YAML文件在OpenCV中的数据结构为FileStorage,打开操作例如: [c ...

  5. 【opencv4】opencv视频教程 C++ 6、图像混合、线性混合、混合权重相加addWeighted()、混合加add()、混合乘multiply()

    上一讲:[opencv4]opencv视频教程 C++ 5.读写图像imread.imwrite.读写像素at<>().修改像素值.ROI区域选择(图像裁剪)Rect.Vec3b与Vec3 ...

  6. 【opencv4】opencv教程 C++ 4、Mat对象(深拷贝:clone()、copyTo(),create()创建图片,zeros()、eye()初始化空白图像,Scalar()创建向量)

    上一讲:[opencv4]opencv视频教程 C++(opencv教程)3.矩阵的掩膜操作(filter2D) 下一讲:[opencv4]opencv视频教程 C++ 5.读写图像imread.im ...

  7. 转载:【opencv入门教程之三】:图片的载入|显示|输出

    本系列文章由@浅墨_毛星云 出品,转载请注明出处. 文章链接: http://blog.csdn.net/poem_qianmo/article/details/20537737 作者:毛星云(浅墨) ...

  8. opencv中Mat与IplImage,CVMat类型之间转换

    opencv中对图像的处理是最基本的操作,一般的图像类型为IplImage类型,但是当我们对图像进行处理的时候,多数都是对像素矩阵进行处理,所以这三个类型之间的转换会对我们的工作带来便利. Mat类型 ...

  9. Opencv C++图像处理(全)

    文章目录 Opencv官方资料 一.入门基础 1.1.头文件说明:#include <opencv2/opencv.hpp> 1.2.头文件说明:#include <opencv2/ ...

最新文章

  1. python实现二叉树遍历(前序遍历、中序遍历、后序遍历)
  2. Can't connect to local MySQL Server throught socket '/var/run/mysqld/mysqld.sock'(2)
  3. Check failed: status == CUDNN_STATUS_SUCCESS (4 vs. 0) CUDNN_STATUS_INTERNAL_ERROR
  4. Linux上搭建Hadoop2.6.3集群以及WIN7通过Eclipse开发MapReduce的demo
  5. python 字符编码的两种方式写法:# coding=utf-8和# -*- coding:utf-8 -*-
  6. 苹果android 对比,苹果安卓旗舰差距有多少?看了这份对比,果粉傻眼了
  7. ISP图像调试工程师——3D和2D降噪(熟悉图像预处理和后处理技术)
  8. navicat设置唯一键——unique
  9. 拓端tecdat|R语言中GLM(广义线性模型),非线性和异方差可视化分析
  10. 最全iOS马甲包审核以及常见审核问题
  11. TeamViewer 如何注册账户?
  12. 20230225在WIN10下安装PR2023失败的解决
  13. android setting之Settings.system设置
  14. 八数码问题的A*算法
  15. Apache Kafka 入门 - Kafka命令详细介绍
  16. 临时和持久化的网络驱动器映射
  17. DPS学习心得(一)
  18. linux系统下文件的上传和下载(rz、sz)
  19. Oracle分组中获取时间最新的一条数据
  20. mipcms模板开发之block(块)内容调用方法

热门文章

  1. C语言:使用函数计算一个数的阶乘
  2. 谷歌翻译 网页嵌入代码_在网页上嵌入Google地图
  3. Permission Denial: opening provider com.ang.providertest.BookProvider from ProcessRecord
  4. mysql function 1064_mysql 创建 function 错误 1064解决方案
  5. 为什么容器内存占用居高不下,频频 OOM(续)
  6. 玩转步进电机控制,自定义中文编程
  7. 高考导数大题中的双变量不等式问题的求解思路
  8. 2018年英语六级作文(附翻译)
  9. MFC 入门级基础知识
  10. 写字板可以保存html,下列不是写字板可以保存的格式是()