opencv3中的imwrite函数

54 篇文章 0 订阅
47 篇文章 2 订阅

opencv3中的imwrite函数是用来输出图像到文件,其声明如下:

CV_EXPORTS_W bool imwrite( const String& filename, InputArray img,
              const std::vector<int>& params = std::vector<int>());

/** @brief Reads an image from a buffer in memory.

The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or
contains invalid data, the function returns an empty matrix ( Mat::data==NULL ).

See cv::imread for the list of supported formats and flags description.

@note In the case of color images, the decoded images will have the channels stored in **B G R** order.
@param buf Input array or vector of bytes.
@param flags The same flags as in cv::imread, see cv::ImreadModes.
*/

第一个参数const String& filename表示需要写入的文件名,必须要加上后缀,比如“123.png”。
第二个参数InputArray img表示Mat类型的图像数据。
第三个参数const std::vector& params表示为特定格式保存的参数编码,它有一个默认值std::vector< int >(),所以一般情况下不用写。

示例程序:

#include <opencv2/opencv.hpp>
#include <vector>

using namespace std;
using namespace cv;//包含cv命名空间
void createAlpha(Mat&);

int main()
{
    Mat mat(480,360,CV_8UC4);//创建带Alpha通道的Mat
    createAlpha(mat);

    vector<int>compression_params;
    compression_params.push_back(IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    try {
        imwrite("D:\\Alppa.png",mat,compression_params);
        imshow("generated png file", mat);
        fprintf(stdout,"generate a png file in D\n");
    }
    catch (runtime_error& ex){
        fprintf(stderr,"generate file error:%s\n",ex.what());//捕获错误
        return 1;
    }


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

        }
    }

}

以上代码会在D盘根目录生成一个Alppa.png。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值