首页 > 其他 > 详细

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

时间:2016-07-16 00:01:07      阅读:1247      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!