opencv从磁盘加载一张图片非常简单,通过cv::imread即可,代码如下:
cv::Mat src_mat = cv::imread("1.jpg"); //读取图片1.jpg,imread会将图片内容解码成yuv或rgb存放到Mat对象 cv::Mat dst_mat = src_mat(cv::Rect(100, 100, 1600, 900)); //获取图片固定区域的内容 std::vector<uchar> jpg_buff; bool ret = cv::imencode(".jpg", dst_mat, jpg_buff);//对固定区域的内容重新进行jpg编码,生成jpg图片,存入jpg_buff FILE *file = fopen("2.jpg", "wb"); if (file != nullptr) { fwrite(jpg_buff.data(), 1, jpg_buff.size(), file); //将jpg图片写入内存 fclose(file); }
然而,很多情况,程序需要从内存中加载图片,例如通过网络上传的图片。很显然,这样的图片不能写入磁盘,然后再通过cv::imread读取,效率太低了。因此,需要从内存直接加载。然后通过cv::imdecode将图片解码成cv::Mat,代码如下:
FILE *file = fopen("1.jpg", "rb"); uchar *mem_pic = nullptr; long size = 0; if (file != nullptr) { fseek(file, 0, SEEK_END); size = ftell(file); fseek(file, 0, SEEK_SET); mem_pic = new uchar[size]; fread(mem_pic, 1, size, file); fclose(file); } cv::_InputArray pic_arr(mem_pic, size); cv::Mat src_mat = cv::imdecode(pic_arr, CV_LOAD_IMAGE_COLOR); cv::Mat dst_src = src_mat(cv::Rect(100, 100, 1600, 900)); std::vector<uchar> pic_buff; bool ret = cv::imencode(".jpg", dst_src, pic_buff); file = fopen("3.jpg", "wb"); if (file != nullptr) { fwrite(pic_buff.data(), 1, pic_buff.size(), file); fclose(file); }
cv::_Array还可以使用std::vector代替,代码如下:
FILE *file = fopen("1.jpg", "rb"); uchar *mem_pic = nullptr; long size = 0; if (file != nullptr) { fseek(file, 0, SEEK_END); size = ftell(file); fseek(file, 0, SEEK_SET); mem_pic = new uchar[size]; fread(mem_pic, 1, size, file); fclose(file); } //cv::_InputArray pic_arr(mem_pic, size); std::vector<uchar> pic_vec(mem_pic, mem_pic + size); cv::Mat src_mat = cv::imdecode(pic_vec, CV_LOAD_IMAGE_COLOR); cv::Mat dst_src = src_mat(cv::Rect(200, 200, 400, 225)); std::vector<uchar> pic_buff; bool ret = cv::imencode(".jpg", dst_src, pic_buff); file = fopen("3.jpg", "wb"); if (file != nullptr) { fwrite(pic_buff.data(), 1, pic_buff.size(), file); fclose(file); }
标签:buff,pic,jpg,opencv,内存,file,size,cv,加载 From: https://www.cnblogs.com/lidabo/p/17648477.html