輸出圖像到文件 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)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM