在工程應用中,通常有需要用網絡傳輸圖片的需求,考慮網絡帶寬的限制,無法直接將原始圖片進行傳輸。使用opencv中的imencode與imdecode函數進行圖像壓縮與解壓
string fname = "D:/image.jpg";
//! 以二進制流方式讀取圖片到內存
FILE* pFile = fopen(fname.c_str(), "rb");
fseek(pFile, 0, SEEK_END);
long lSize = ftell(pFile);
rewind(pFile);
char* pData = new char[lSize];
fread(pData, sizeof(char), lSize, pFile);
fclose(pFile);
//! 解碼內存數據,變成cv::Mat數據
cv::Mat img_decode;
vector<uchar> data;
for (int i = 0; i < lSize; ++i){
data.push_back(pData[i]);
}
img_decode = cv::imdecode(data, CV_LOAD_IMAGE_COLOR);
cv::flip(img_decode, img_decode, -1);
img_decode.channels();
//! 將cv::Mat數據編碼成數據流
vector<unsigned char> img_encode;
cv::imencode(".jpg", img_decode, img_encode);
unsigned char *encode_data = new unsigned char[lSize];
for (int i = 0; i<lSize; i++){
encode_data[i] = img_encode[i];
}