c++写jpg图片转mat格式的代码
由于JPG格式是一种压缩格式,所以需要使用第三方库来读取和处理JPG图像。在C++中,常用的图像处理库有OpenCV和Boost.GIL。
以下是使用OpenCV库将JPG图像转换为Mat格式的代码示例:
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
// 读取JPG图像
Mat image = imread("example.jpg", IMREAD_COLOR);
if (image.empty()) {
printf("Could not read the image: %s\n", "example.jpg");
return -1;
}
// 显示图像
namedWindow("JPG Image", WINDOW_NORMAL);
imshow("JPG Image", image);
waitKey(0);
return 0;
}
在上面的代码中,首先使用imread()函数读取JPG图像,并将其存储到Mat类型的变量image中。如果读取失败,将输出一条错误消息并退出程序。然后使用namedWindow()函数创建一个窗口,将图像显示在窗口中,并使用waitKey()函数等待用户按下键盘上的任意键。最后返回0表示程序运行成功。
如果使用Boost.GIL库,可以参考以下代码示例:
#include <iostream>
#include <boost/gil/extension/io/jpeg_dynamic_io.hpp>
#include <boost/gil/image.hpp>
#include <boost/gil/typedefs.hpp>
using namespace boost::gil;
int main() {
// 读取JPG图像
rgb8_image_t image;
jpeg_read_image("example.jpg", image);
// 显示图像大小
std::cout << "Image size: " << image.dimensions() << std::endl;
return 0;
}
在上面的代码中,首先定义一个rgb8_image_t类型的变量image,并使用jpeg_read_image()函数将JPG图像读取到该变量中。然后使用dimensions()函数获取图像的大小,并输出到控制台中
原文地址: https://www.cveoy.top/t/topic/eRrX 著作权归作者所有。请勿转载和采集!