1. 程式人生 > 其它 >opencv的Mat資料和JPG資料的相互轉化,及base64資料流的轉化

opencv的Mat資料和JPG資料的相互轉化,及base64資料流的轉化

轉載:https://blog.csdn.net/baidu_31872269/article/details/86010156

Mat 一個影象資料轉化為jpg圖片buffer 壓縮率可以變為原來的 1/ 15 - 1 / 10
Mat2Img.h

#ifndef MAT2IMG_H
#define MAT2IMG_H
#include "opencv2/opencv.hpp"
#include <vector>
#include "image_base64.h"

class Mat2Img 
{
        

public:
    static int MatToByteArray(const
cv::Mat mat, std::vector<unsigned char>& buff) { if (mat.empty()) { return 0; } std::vector<int> param = std::vector<int>(2); param[0] = CV_IMWRITE_JPEG_QUALITY; param[1] = 95; // default(95) 0-100 cv::imencode(".jpg", mat, buff, param);
return 0; } static int JPEGToMat(cv::Mat &matImage, std::vector<unsigned char> buff) { if (buff.empty()) { return -1; } if ((buff[0] == 0xFF && buff[1] == 0xD8)) { matImage = cv::imdecode(buff, CV_LOAD_IMAGE_COLOR); }
else { buff.insert(buff.begin(), 0xFF); buff.insert(buff.begin()+1, 0xD8); matImage = cv::imdecode(buff, CV_LOAD_IMAGE_COLOR); } return 0; } static int Mat2Base64(cv::Mat &image, std::string &base64) { std::vector<unsigned char> cut_jpg; // Mat -> jpg cut_jpg.clear(); Mat2Img::MatToByteArray(image, cut_jpg); base64 = ImageBase64::encode(cut_jpg.data(), cut_jpg.size()); return 0; } static int Base2Mat(std::string &base64, cv::Mat &image) { int outLen = 0; std::string str1 = ImageBase64::decode(base64.c_str(), base64.size(), outLen); std::vector<uchar> baseJpgVec; baseJpgVec.assign(&str1.data()[0], &str1.data()[outLen]); int ret = Mat2Img::JPEGToMat(image, baseJpgVec); if (ret != 0) { return ret; } return 0; } }; #endif

有時候也會用到jpg 資料轉化為Base64 的字串資料,方便網路傳輸
image_base64.h

#ifndef TESTFACEAPI_TESTFACEAPI_IMAGE_BASE64_H
#define TESTFACEAPI_TESTFACEAPI_IMAGE_BASE64_H
#include <string>
// 對圖片進行base64編碼解碼類
class ImageBase64
{
public:

    /*編碼
    DataByte
    [in]輸入的資料長度,以位元組為單位
    */
    static const std::string encode(const unsigned char* Data, int DataByte);
    /*解碼
    DataByte
    [in]輸入的資料長度,以位元組為單位
    OutByte
    [out]輸出的資料長度,以位元組為單位,請不要通過返回值計算
    輸出資料的長度
    */
    static const std::string decode(const char* Data, int DataByte, int& OutByte);
    // 傳入圖片地址進行base64編碼示例
    static std::string file2base64(const std::string& file_path);
};
#endif

image_base64.cpp

#include "image_base64.h"
#include <vector>
#include "opencv2\opencv.hpp"

static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";

static inline bool is_base64(unsigned char c) {
    return (isalnum(c) || (c == '+') || (c == '/'));
}

const std::string ImageBase64::encode(const unsigned char* Data, int DataByte)
{
    //編碼表  
    const char EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    //返回值  
    std::string str_encode;
    unsigned char tmp[4] = { 0 };
    int line_length = 0;
    for (int i = 0; i < (int)(DataByte / 3); i++)
    {
        tmp[1] = *Data++;
        tmp[2] = *Data++;
        tmp[3] = *Data++;
        str_encode += EncodeTable[tmp[1] >> 2];
        str_encode += EncodeTable[((tmp[1] << 4) | (tmp[2] >> 4)) & 0x3F];
        str_encode += EncodeTable[((tmp[2] << 2) | (tmp[3] >> 6)) & 0x3F];
        str_encode += EncodeTable[tmp[3] & 0x3F];
        if (line_length += 4, line_length == 76)
        {
            str_encode += "\r\n"; 
            line_length = 0;
        }
    }
    //對剩餘資料進行編碼  
    int mod = DataByte % 3;
    if (mod == 1)
    {
        tmp[1] = *Data++;
        str_encode += EncodeTable[(tmp[1] & 0xFC) >> 2];
        str_encode += EncodeTable[((tmp[1] & 0x03) << 4)];
        str_encode += "==";
    }
    else if (mod == 2)
    {
        tmp[1] = *Data++;
        tmp[2] = *Data++;
        str_encode += EncodeTable[(tmp[1] & 0xFC) >> 2];
        str_encode += EncodeTable[((tmp[1] & 0x03) << 4) | ((tmp[2] & 0xF0) >> 4)];
        str_encode += EncodeTable[((tmp[2] & 0x0F) << 2)];
        str_encode += "=";
    }

    return str_encode;
}

const std::string ImageBase64::decode(const char* Data, int DataByte, int& OutByte)
{
    //解碼錶  
    const char DecodeTable[] =
    {
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        62, // '+'  
        0, 0, 0,
        63, // '/'  
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9'  
        0, 0, 0, 0, 0, 0, 0,
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
        13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z'  
        0, 0, 0, 0, 0, 0,
        26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
        39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z'  
    };
    //返回值  
    std::string str_decode;
    int n_value = 0;
    int i = 0;
    while (i < DataByte)
    {
        if (*Data != '\r' && *Data != '\n')
        {
            n_value = DecodeTable[*Data++] << 18;
            n_value += DecodeTable[*Data++] << 12;
            str_decode += (n_value & 0x00FF0000) >> 16;
            OutByte++;
            if (*Data != '=')
            {
                n_value += DecodeTable[*Data++] << 6;
                str_decode += (n_value & 0x0000FF00) >> 8;
                OutByte++;
                if (*Data != '=')
                {
                    n_value += DecodeTable[*Data++];
                    str_decode += n_value & 0x000000FF;
                    OutByte++;
                }
            }
            i += 4;
        }
        else// 回車換行,跳過  
        {
            Data++;
            i++;
        }
    }
    return str_decode;
}

std::string ImageBase64::file2base64(const std::string& file_path)
{
    cv::Mat img = cv::imread(file_path);
    if (img.empty())
    {
        return "";
    }
    std::vector<uchar> vec_img;                               //Mat 圖片資料轉換為vector<uchar>  
    std::vector<int> vec_compression_params;
    vec_compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
    vec_compression_params.push_back(90);
    cv::imencode(".jpg", img, vec_img, vec_compression_params);
    // base64;
    std::string img_base64 = encode(vec_img.data(), vec_img.size());
    return img_base64;
}

main.cpp

int main(int argc, char * argv[])
{
    char * path1 = "C:\\Users\\FaceOS\\Pictures\\faceCheck\\20181207102753.jpg";
    cv::Mat Image = cv::imread(path1);

    cv::imshow("show", Image);
// Mat 轉化為jpg
    std::vector<unsigned char> buff_jpg;
    
    int ret = Mat2Img::MatToByteArray(Image, buff_jpg);
// jpg 轉化為Base64

    std::string str = ImageBase64::encode(buff_jpg.data(), buff_jpg.size());
// Base64 字串轉化為jpg 的string
    int outLen = 0;
    std::string str1 = ImageBase64::decode(str.c_str(), str.size(), outLen);

    cv::Mat MatFromBase;
    std::vector<uchar> baseJpgVec;
    // jpg string 拷貝到jpg 陣列buffer
    baseJpgVec.assign(&str1.data()[0], &str1.data()[outLen]);
    //jpg buffer 轉化為Mat
    Mat2Img::JPEGToMat(MatFromBase, baseJpgVec);
    
     cv::imshow("show1", MatFromBase);
     
     cv::waitKey(0);
}