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

本文提供了一个使用C++和Python进行图片编码和解码的示例。在C++部分,程序读取图片,将其编码并保存到文件中,再从文件读取编码内容并解码,最后显示解码后的图片。Python部分同样实现了图片的编码、保存、读取和解码,并使用OpenCV库进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

这是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.  
  9. using namespace boost::filesystem;

  10. namespace newfs = boost::filesystem;

  11. using namespace cv;

  12.  
  13. int main(int argc, char ** argv)

  14. {

  15. cv::Mat img_encode;

  16. img_encode = imread("../res/test.png", CV_LOAD_IMAGE_COLOR);

  17.  
  18. //encode image and save to file

  19. std::vector<uchar> data_encode;

  20. imencode(".png", img_encode, data_encode);

  21. std::string str_encode(data_encode.begin(), data_encode.end());

  22.  
  23. path p("../res/imgencode_cplus.txt");

  24. newfs::ofstream ofs(p);

  25. assert(ofs.is_open());

  26. ofs << str_encode;

  27. ofs.flush();

  28. ofs.close();

  29.  
  30. //read image encode file and display

  31. newfs::fstream ifs(p);

  32. assert(ifs.is_open());

  33. std::stringstream sstr;

  34. while(ifs >> sstr.rdbuf());

  35. ifs.close();

  36.  
  37. Mat img_decode;

  38. std::string str_tmp = sstr.str();

  39. std::vector<uchar> data(str_tmp.begin(), str_tmp.end());

  40. img_decode = imdecode(data, CV_LOAD_IMAGE_COLOR);

  41. imshow("pic",img_decode);

  42. cvWaitKey(10000);

  43.  
  44. return 0;

  45. }

 

使用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.  
  11. #save to file

  12. fw = open('img_encode.txt', 'w')

  13. fw.write(str_encode)

  14. fw.flush

  15. fw.close

  16.  
  17. #decode and display

  18. nparr = np.fromstring(str_encode, np.uint8)

  19. img_decode = cv2.imdecode(nparr, 1)

  20. cv2.imshow("img_decode", img_decode)

  21. cv2.waitKey(10000)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值