码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-07-16 00:04:19      阅读:1909      评论:0      收藏:0      [点我收藏+]

标签:

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

filename

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

img

一般为一个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)

 

技术分享

 

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

标签:

原文地址:http://www.cnblogs.com/Xiaoyan-Li/p/5674806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!