cv:mat读取图片并显示
int main()
{
cv::Mat mat = cv::imread("/home/oceanstar/image/aa.jpg");
if(mat.empty())
{
cout << "图像不能加载!"<< endl;
return -1;
}
imshow("MyWindow", mat);
waitKey(0);
return 0;
}
char*转为mat
cv::Mat char_to_mat(char *image_buf, int image_len){
cv::Mat mat;
string str2(image_buf, image_len);
std::vector<char> vec_data1(str2.c_str(), str2.c_str() + str2.size());
mat = cv::imdecode(vec_data1, -1).clone();
return mat;
}
char[]与mat
#include <string>
#include <iostream>
#include <time.h>
#include <opencv2/highgui/highgui.hpp>
#include <fstream>
using namespace std;
using namespace cv;
const int MAX = 1024 * 1920 * 3;
bool write_image(const string& filename, char *pBuffer, int length){
ofstream fout(filename, ios::binary);
if(!fout){
printf("can't open = %s\n", filename.c_str());
return false;
}
fout.write(pBuffer,length);
fout.close();
return true;
}
int main()
{
cv::Mat img2 = cv::imread("/home/oceanstar/image/aa.jpg");
if(img2.empty())
{
cout << "图像不能加载!"<< endl;
return -1;
}
char p[MAX];
std::vector<uchar> buff;
cv::imencode(".jpg", img2, buff);
memset(p, 0, MAX);
memcpy(p, reinterpret_cast<char*>(&buff[0]), buff.size());
int length = buff.size();
char * buffer = reinterpret_cast<char *>(p);
write_image("/home/oceanstar/image/vvvv.jpg", buffer, length );
return 0;
}
uchar*与mat
#include <string>
#include <iostream>
#include <time.h>
#include <opencv2/highgui/highgui.hpp>
#include <fstream>
using namespace std;
using namespace cv;
const int img_width=1920;
const int img_height = 1024;
Mat ucharToMat(const uchar *p2)
{
Mat img(Size(img_width, img_height),CV_8UC3);
for (int i = 0; i < img_width * img_height * 3; i++)
{
img.at<Vec3b>(i / (img_width * 3), (i % (img_width * 3)) / 3)[i % 3] = p2[i];
}
return img;
}
uchar* matToUchar(Mat img, uchar *p1)
{
for (int i = 0; i < img_width * img_height * 3; i++)
{
p1[i]= (uchar)img.at<Vec3b>(i / (img_width * 3), (i % (img_width * 3)) / 3)[i % 3];
}
return p1;
}
int main()
{
cv::Mat img2 = cv::imread("/home/oceanstar/image/aa.jpg");
if(img2.empty())
{
cout << "图像不能加载!"<< endl;
return -1;
}
auto *p = new uchar[img_width * img_height * 3];
matToUchar(img2, p);
for (int i = 0; i < img_width * img_height * 3; i++){
cout << (int)p[i] << endl;
}
Mat img = ucharToMat(p);
imshow("img",img);
waitKey(0);
return 0;
}
cv::Mat转std::string
cv::Mat mat = cv::imread("d:\\1.jpg");
std::string str;
std::vector<unsigned char> buff;
cv::imencode(".jpg", mat, buff);
str.resize(buff.size());
memcpy(&str[0], buff.data(), buff.size());
c/c++编程:读取文本&图片转为二进制流
uchar和Mat之间的相互转换
c++ string转char*