输出图像到文件 imwrite()[OpenCV 笔记7]

bool imwrite(const string& filename, InputArray img, const vector<int>& params=vector<int>());

filename

待写入的文件名。保存图像的格式由扩展名决定。

img

一般为一个Mat类型的图像。

图像要求:单通道或三通道图像,8bit或16bit无符号数,其他类型输入需要用函数进行转换 (这个还是挺重要的,之前想存一个float型的Mat, 发现并没有好的办法,最后解决方案是存成xml文件):

  • convertTo: 转换数据类型不同的Mat
  • cvtColor: 转换不同通道的Mat (利用第四个参数)

params

特定格式保存的参数编码:

  • JPEG:params表示0到100的图片质量(CV_IMWRITE_JPEG_QUALITY),默认值为95;
  • PNG:params表示压缩级别(CV_IMWRITE_PNG_COMPRESSION),从0到9,其值越大,压缩尺寸越小,压缩时间越长;
  • PPM / PGM / PBM:params表示二进制格式标志(CV_IMWRITE_PXM_BINARY),取值为0或1,默认值是1。

实例:生成图片并保存到电脑

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
//#include <opencv2/imgcodecs/imgcodecs.hpp>
//#include <opencv2/imgproc/imgproc.hpp>
#include <vector>

void createAlphaMat(cv::Mat &mat)
{
    for (int i=0; i<mat.rows; i++) {
        for (int j = 0; j<mat.cols; ++j) {
            cv::Vec4b& rgba = mat.at<cv::Vec4b>(i,j);
            rgba[0] = UCHAR_MAX;
            rgba[1] = cv::saturate_cast<uchar>((float (mat.cols-j))/((float)mat.cols)*UCHAR_MAX);
            rgba[2] = cv::saturate_cast<uchar>((float (mat.rows-i))/((float)mat.rows)*UCHAR_MAX);
            rgba[3] = cv::saturate_cast<uchar>(0.5*(rgba[1]+rgba[2]));
        }
    }
}

int main(){
    // create Mat with alpha channel
    cv::Mat mat(480, 640, CV_8UC4);
    createAlphaMat(mat);
    
    std::vector<int> compression_params;
    if(CV_VERSION_MAJOR==3)
        compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
        // if OpenCV2 comment this
    else
        compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
    
    // show image
    try{
        imwrite("alpha.png", mat, compression_params);
        imshow("Created PNG", mat);
        fprintf(stdout, "Finish creating image with alpha channel.\n");
        cv::waitKey(0);
    }
    catch(std::runtime_error& ex){
        fprintf(stderr, "Error when converting to PNG: %s\n", ex.what());
        return 1;
    }
    return 0;
}

CMakeLists.txt

cmake_minimum_required (VERSION 2.8)
project (WriteImage)

# find OpenCV packages
find_package( OpenCV REQUIRED PATHS /usr/local/Cellar/opencv3/3.1.0_3/share/OpenCV/)
include_directories( ${OpenCV_INCLUDE_DIRS} )

# add the executable
add_executable (WriteImage WriteImage.cxx)
target_link_libraries(WriteImage opencv_core opencv_highgui opencv_imgproc opencv_imgcodecs)

 

 

posted @ 2016-07-15 21:26  TinaSmile  阅读(14142)  评论(1编辑  收藏  举报