opencv:图像的创建和储存


示例代码:

#include <opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;
void creatAlphaMat(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.rows - i)) / ((float)mat.rows)*UCHAR_MAX);
            rgba[3] = saturate_cast<uchar>(0.5*(rgba[1] + rgba[2]));
        }
    }
}
int main()
{
    //创建带Alpha通道的 Mat
    Mat mat(480, 640, CV_8UC4);
    creatAlphaMat(mat);
    vector<int>compression_params;
    compression_params.push_back(IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    try{
        imwrite("透明值图.png", mat, compression_params);
        imshow("生成的PNG图", mat);
        fprintf(stdout, "PNG图片文件的数据保存完毕");
        waitKey(0);
    }
    catch (runtime_error& ex){
        fprintf(stderr, "图像转换发生错误:%s\n", ex.what());
        return 1;
    }
    return 0;
}

 

  运行结果:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM