Working with Images in C++: CImg and STB Image Libraries
Image processing is one of the key tasks in computer graphics, computer vision, and web technologies. C++ has no built-in tools for working with raster images, but there are many third-party libraries. In this article, we will look at two popular and easy-to-use libraries: CImg (for high-level processing) and STB Image (for fast loading/saving of popular formats).
1. CImg: A Universal Library for Image Processing
CImg (C++ Template Image Processing Library) is a header-only library that provides a wide range of functions for loading, displaying, filtering, and analyzing images. It supports BMP, JPEG, PNG, TIFF, and other formats (with additional libraries such as libpng, libjpeg).
Installation and Setup
Download the latest version from the official website. Then simply include the header file:
#include "CImg.h"using namespace cimg_library;Basic Operations with CImg
Let's look at loading, resizing, and applying a Gaussian filter:
#include "CImg.h"#include <iostream>
int main() { // Load image (supports BMP, JPG, PNG, etc.) CImg<unsigned char> img("input.jpg"); // Resize to 400x300 CImg<unsigned char> resized = img.resize(400, 300); // Apply Gaussian blur (radius 3) CImg<unsigned char> blurred = resized.get_blur(3.0f); // Save the result blurred.save("output.jpg"); std::cout << "Image processed!" << std::endl; return 0;}Additional CImg Features
- Filters: blur, sharpen, median filter, morphological operations.
- Color transformations: conversion to grayscale, HSV, Lab.
- Histogram: construction and equalization.
- Drawing: lines, circles, text on an image.
- Display: built-in window for viewing (requires X11 on Linux or WinAPI on Windows).
2. STB Image: Fast Loading and Saving
STB Image is a set of single-header libraries by Sean Barrett, designed for reading/writing images in PNG, JPG, BMP, GIF, and other formats. The main advantage is minimalism and speed. No installation required, just include the stb_image.h and stb_image_write.h files.
Setup
Download the files from GitHub. To use, define the STB_IMAGE_IMPLEMENTATION macro in exactly one .cpp file:
#define STB_IMAGE_IMPLEMENTATION#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION#include "stb_image_write.h"Example: Loading PNG and Saving as JPG
#include <iostream>
#define STB_IMAGE_IMPLEMENTATION#include "stb_image.h"#define STB_IMAGE_WRITE_IMPLEMENTATION#include "stb_image_write.h"
int main() { int width, height, channels; // Load image (returns pixel array in RGB/RGBA format) unsigned char* img = stbi_load("input.png", &width, &height, &channels, 3); if (!img) { std::cerr << "Error loading image!" << std::endl; return -1; } // Save as JPEG with quality 90 stbi_write_jpg("output.jpg", width, height, 3, img, 90); // Free memory stbi_image_free(img); std::cout << "Conversion complete!" << std::endl; return 0;