opencv的Mat数据和JPG数据的相互转化

Mat 一个图像数据转化为jpg图片buffer 压缩率可以变为原来的 1/ 15 - 1 / 10
Mat2Img.h

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

class Mat2Img 
{
		

public:
	static int MatToByteArray(const cv::Mat mat, std::vector& buff)
	{
		if (mat.empty()) {
			return 0;
		}
		std::vector param = std::vector(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 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 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 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 
// 对图片进行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 
#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 vec_img;                               //Mat 图片数据转换为vector  
    std::vector 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 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 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);
}

你可能感兴趣的:(c++,图像处理)