加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

opencvimencode和imdecode使用,用于网络传输图片

(2018-12-06 16:21:59)
分类: c#c c

转:https://blog.csdn.net/tt_ren/article/details/53227900

这是C++版本的。程序首先读入一个图片。然后encode,之后把encode后的内容写入文件(实际应用可以发送到网络)。
第二步,从文件读取encode的内容。然后解码decode。转换为mat格式,显示出来。


#include
#include
#include
#include
#include
#include
#include
 
using namespace boost::filesystem;
namespace newfs = boost::filesystem;
using namespace cv;
 
int main(int argc, char ** argv)
{
    cv::Mat img_encode;
    img_encode = imread("../res/test.png", CV_LOAD_IMAGE_COLOR);
 
    //encode image and save to file
    std::vector data_encode;
    imencode(".png", img_encode, data_encode);
    std::string str_encode(data_encode.begin(), data_encode.end());
 
    path p("../res/imgencode_cplus.txt");
    newfs::ofstream ofs(p);
    assert(ofs.is_open());
    ofs << str_encode;
    ofs.flush();
    ofs.close();
 
    //read image encode file and display
    newfs::fstream ifs(p);
    assert(ifs.is_open());
    std::stringstream sstr;
    while(ifs >> sstr.rdbuf());
    ifs.close();
 
    Mat img_decode;
    std::string str_tmp = sstr.str();
    std::vector data(str_tmp.begin(), str_tmp.end());
    img_decode = imdecode(data, CV_LOAD_IMAGE_COLOR);
    imshow("pic",img_decode);
    cvWaitKey(10000);
 
    return 0;
}

使用python的例子。

import sys
import cv2   
import numpy as np
def img_endecode( img):
    #type img: cv::mat
    #encode image from cv::mat
    img_encode = cv2.imencode('.png', img)[1]
    data_encode = np.array(img_encode)
    str_encode = data_encode.tostring()
   
    #save to file
    fw = open('img_encode.txt', 'w')
    fw.write(str_encode)
    fw.flush
    fw.close  
   
    #decode and display
    nparr = np.fromstring(str_encode, np.uint8)
    img_decode = cv2.imdecode(nparr, 1)
    cv2.imshow("img_decode", img_decode)
    cv2.waitKey(10000)

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有