opencvimencode和imdecode使⽤,⽤于⽹络传输图⽚
这是C++版本的。程序⾸先读⼊⼀个图⽚。然后encode,之后把encode后的内容写⼊⽂件(实际应⽤可以发送到⽹络)。第⼆步,从⽂件读取encode的内容。然后解码decode。转换为mat格式,显⽰出来。
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <iostream>
#include <sstream>
#include <string>
#include <opencv2/opencv.hpp>
#include <vector>
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<uchar> data_encode;
imencode(".png", img_encode, data_encode);
std::string str_encode(data_encode.begin(), d());
path p("../res/");
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;
include和contain
std::string str_tmp = sstr.str();
std::vector<uchar> data(str_tmp.begin(), d());
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 = string()
#save to file
fw = open('', '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)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论