当前位置:   article > 正文

opencv imencode和imdecode使用,用于网络传输图片_c++ opencv imencode

c++ opencv imencode

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

  1. #include <boost/filesystem.hpp>
  2. #include <boost/filesystem/fstream.hpp>
  3. #include <iostream>
  4. #include <sstream>
  5. #include <string>
  6. #include <opencv2/opencv.hpp>
  7. #include <vector>
  8. using namespace boost::filesystem;
  9. namespace newfs = boost::filesystem;
  10. using namespace cv;
  11. int main(int argc, char ** argv)
  12. {
  13. cv::Mat img_encode;
  14. img_encode = imread("../res/test.png", CV_LOAD_IMAGE_COLOR);
  15. //encode image and save to file
  16. std::vector<uchar> data_encode;
  17. imencode(".png", img_encode, data_encode);
  18. std::string str_encode(data_encode.begin(), data_encode.end());
  19. path p("../res/imgencode_cplus.txt");
  20. newfs::ofstream ofs(p);
  21. assert(ofs.is_open());
  22. ofs << str_encode;
  23. ofs.flush();
  24. ofs.close();
  25. //read image encode file and display
  26. newfs::fstream ifs(p);
  27. assert(ifs.is_open());
  28. std::stringstream sstr;
  29. while(ifs >> sstr.rdbuf());
  30. ifs.close();
  31. Mat img_decode;
  32. std::string str_tmp = sstr.str();
  33. std::vector<uchar> data(str_tmp.begin(), str_tmp.end());
  34. img_decode = imdecode(data, CV_LOAD_IMAGE_COLOR);
  35. imshow("pic",img_decode);
  36. cvWaitKey(10000);
  37. return 0;
  38. }


使用python的例子。

  1. import sys
  2. import cv2
  3. import numpy as np
  4. def img_endecode( img):
  5. #type img: cv::mat
  6. #encode image from cv::mat
  7. img_encode = cv2.imencode('.png', img)[1]
  8. data_encode = np.array(img_encode)
  9. str_encode = data_encode.tostring()
  10. #save to file
  11. fw = open('img_encode.txt', 'w')
  12. fw.write(str_encode)
  13. fw.flush
  14. fw.close
  15. #decode and display
  16. nparr = np.fromstring(str_encode, np.uint8)
  17. img_decode = cv2.imdecode(nparr, 1)
  18. cv2.imshow("img_decode", img_decode)
  19. cv2.waitKey(10000)


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/523046
推荐阅读
相关标签
  

闽ICP备14008679号