C++ JPG to Mat Conversion: OpenCV & Boost.GIL Examples
JPG is a compressed format, requiring third-party libraries for reading and processing. In C++, popular choices include OpenCV and Boost.GIL.
Using OpenCV
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
// Read JPG image
Mat image = imread('example.jpg', IMREAD_COLOR);
if (image.empty()) {
printf("Could not read the image: %s\n", "example.jpg");
return -1;
}
// Display image
namedWindow('JPG Image', WINDOW_NORMAL);
imshow('JPG Image', image);
waitKey(0);
return 0;
}
This code reads the JPG image using imread(), stores it in a Mat variable, displays it in a window using namedWindow() and imshow(), and waits for user input with waitKey().
Using 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() {
// Read JPG image
rgb8_image_t image;
jpeg_read_image('example.jpg', image);
// Display image size
std::cout << "Image size: " << image.dimensions() << std::endl;
return 0;
}
This example demonstrates reading the JPG image into a rgb8_image_t using jpeg_read_image() and then printing the image dimensions.
Choose the library that best suits your project needs. Both OpenCV and Boost.GIL offer comprehensive image processing functionalities.
原文地址: https://www.cveoy.top/t/topic/nZEV 著作权归作者所有。请勿转载和采集!