imageresizer_web_logo

ImageResizer C++ library

v2.1.1

Table of contents

Overview

ImageResizer C++ library provides image resizing. The library contains two mutually exclusive implementations. The software implementation uses SIMD-optimized bicubic interpolation (Keys cubic, a = -0.75). The library implements a two-pass separable filter with platform-specific vectorization: AVX2 or SSSE3 kernels on x86/x64 (the level is selected at run time, see Portability), NEON on ARM64, and portable C++ code for other architectures and for CPUs without these instruction sets. Tile-based processing ensures L2 cache locality for upscale paths, while a row-cache strategy is used for downscale. The G2D implementation is a wrapper around the G2D API, which is used to work with the i.MX GPU. Resizing is single threaded by default and can optionally be spread over image rows with OpenMP, see Multithreading. Apart from OpenMP (supplied with the compiler, optional) and the G2D library (used only if it is found at build time) the library doesn’t have third-party dependencies. Input data must be 3-byte-per-pixel interleaved format (BGR24, RGB24 and YUV24). The library uses C++17 standard and is compatible with Linux and Windows.

ImageResizer is general-purpose software: it is not tied to any sector or application, and the developer of a program decides what the program does with it.

Versions

Table 1 - Library versions.

Version Release date What’s new
1.0.0 03.04.2026 First version of the library.
1.0.1 05.04.2026 Fixed alignments in data structures.
2.0.0 23.08.2026 - setMaxThreads(…) and getMaxThreads() methods added to control how many CPU cores the resizer may use.
- Breaking change: the numThreads parameter of resize(…) is removed, the thread count is set with setMaxThreads(…) only.
- OpenMP is optional now.
- Resizing to the same size is a plain copy now instead of a full filter pass (~8 times faster).
- Fixed out-of-bounds read in the ARM64 NEON horizontal pass for source images narrower than 6 pixels.
- Fixed undefined behaviour (misaligned 32-bit store) in the x86 horizontal pass.
- Fixed the build in the Debug, RelWithDebInfo and MinSizeRel configurations on GCC/Clang: the SSSE3/AVX2 flags were applied to Release only while the kernels use the intrinsics unconditionally.
2.1.0 04.09.2026 - Added a G2D pipeline for i.MX.
2.1.1 16.10.2026 - The SSSE3/AVX2 flags are no longer applied to the whole library. The SSSE3 and AVX2 kernels are built in separate files and the instruction set is selected at run time (CPUID). Added portable C++ kernels and the CMake option IMAGERESIZER_ENABLE_SIMD. The library runs on any x86-64 CPU (it stopped with an illegal instruction on a CPU without AVX2).
- Fixed: the interpolation weights were calculated with fused multiply-add on some compilers and targets (default of GCC for C++, ARM64), so the result differed between builds for some sizes (for example 1920x1080 -> 1919x1079). The results are identical on all compilers and architectures now (-ffp-contract=off).
- resize(…) checks the arguments: sizes are limited to 1 - 65536 (larger values overflowed the int arithmetic of the row offsets and let the memory of the lookup tables grow without limit), overlapping source and destination buffers are rejected, the destination is not changed if the arguments are invalid or if memory allocation fails.
- A failed memory allocation makes resize(…) return FALSE instead of terminating the application; the object stays usable after the failure.
- Work rows of the threads are kept in the object instead of thread local buffers that were never released.
- Copy and move operations are declared explicitly and are available in the software and in the G2D implementation: in the G2D implementation a copy opens its own G2D device and buffers at its first resize, a move passes them to the new object. A moved-from object stays usable.
- ImageResizer.h is the same with and without G2D: the class layout does not depend on USE_G2D, which is a private definition of the library now.
- G2D: sizes that do not fit the G2D allocator (2 GiB) are rejected.
- Standard C++ only (no compiler extensions), strict compiler warnings, compiler and linker options for exploit mitigation. Fixed the MSVC warning D9025 (/Ob2 overridden by /Ob3).
- Doxygen comments of the header describe limits, thread safety and error behavior. Documentation updated.

Library files

The library supplied by source code only. The user would be given a set of files in the form of a CMake project (repository). The repository structure is shown below:

CMakeLists.txt ------------------- Main CMake file of the library.
src ------------------------------ Folder with source code of the library.
    CMakeLists.txt --------------- CMake file of the library.
    ImageResizer.cpp ------------- C++ implementation file.
    ImageResizer.h --------------- Header file which includes ImageResizer class declaration.
    ImageResizerVersion.h -------- Header file which includes version of the library.
    ImageResizerVersion.h.in ----- CMake service file to generate version file.
    impl ------------------------- Folder with the instruction set specific kernels (internal).
        ImageResizerTable.h ------------------ Header file which includes the lookup table entry and shared constants.
        ImageResizerKernels.h ---------------- Header file which includes the kernel table.
        ImageResizerPortable.cpp ------------- Portable C++ kernels.
        ImageResizerDispatch.cpp ------------- Run-time selection of the kernels (CPUID).
        x86 ---------------------------------- Folder with the x86 kernels.
            ImageResizerHorizontalSsse3.h ---- Horizontal pass (SSSE3 algorithm), included by the two files below.
            ImageResizerSsse3.cpp ------------ SSSE3 kernels.
            ImageResizerAvx2.cpp ------------- AVX2 kernels.
        arm ---------------------------------- Folder with the ARM64 kernels.
            ImageResizerNeon.cpp ------------- NEON kernels.
example -------------------------- Folder for example application.
    CMakeLists.txt --------------- CMake file for example application.
    main.cpp --------------------- Source code file of example application.
static --------------------------- Folder with static resources.
    imageresizer_web_logo.png ---- Web logo image.

ImageResizer class description

ImageResizer class declaration

The ImageResizer class declared in ImageResizer.h file. Class declaration:

namespace rapidpixel
{
/// Image resizer class.
class ImageResizer
{
public:

    /// Default constructor.
    ImageResizer() noexcept;

    /// Class destructor.
    ~ImageResizer();

    /// Copy and move constructors and assignment operators.
    ImageResizer(const ImageResizer& src);
    ImageResizer(ImageResizer&& src) noexcept;
    ImageResizer& operator=(const ImageResizer& src);
    ImageResizer& operator=(ImageResizer&& src) noexcept;

    /// Get the version of the ImageResizer class.
    static std::string getVersion();

    /// Resize image.
    bool resize(uint8_t* src, int srcWidth, int srcHeight,
                uint8_t* dst, int dstWidth, int dstHeight);

    /// Set upper limit for the number of threads used by resize(...).
    void setMaxThreads(int maxThreads);

    /// Get the number of threads resize(...) may use at most.
    int getMaxThreads() const;
};
}

The class declaration is the same in the software and in the G2D implementation: ImageResizer.h does not depend on the build options, so a program needs no macros to use the library. The copy and move constructors and assignment operators are available in both implementations. In the G2D implementation the object opens the G2D device and allocates the G2D buffers at its first resize(…): a copy does not share them and opens its own ones at its first resize(…), a copy assignment keeps the own ones of the object, a move passes them to the new object. A moved-from object stays usable. The class is not thread-safe: calls of the methods of one object must not overlap in time, objects are independent of each other, see Multithreading.

getVersion method

The getVersion() static method returns string of current class version. Method declaration:

static std::string getVersion();

Method can be used without ImageResizer class instance:

std::cout << "ImageResizer version: " << rapidpixel::ImageResizer::getVersion();

Console output:

ImageResizer version: 2.1.1

resize method

The resize(…) method performs image resizing with bicubic interpolation. Method declaration:

bool resize(uint8_t* src, int srcWidth, int srcHeight,
            uint8_t* dst, int dstWidth, int dstHeight);
Parameter Description
src Pointer to source image data. Only 3-byte-per-pixel interleaved data (BGR24, RGB24, YUV24) without row padding. Must not be nullptr. The buffer must contain at least srcWidth * srcHeight * 3 bytes. The data is not modified.
srcWidth Width of source image in pixels. Valid range is 1 - 65536.
srcHeight Height of source image in pixels. Valid range is 1 - 65536.
dst Pointer to destination image data buffer. Must not be nullptr. Must be pre-allocated with size >= dstWidth * dstHeight * 3 bytes.
dstWidth Width of destination image in pixels. Valid range is 1 - 65536.
dstHeight Height of destination image in pixels. Valid range is 1 - 65536.

Returns: TRUE if resizing was successful. FALSE if src or dst is nullptr, if a size is outside of the range 1 - 65536, if the source and destination buffers overlap, if the image is too large for the address space, if the library could not allocate memory or (G2D implementation) if a size does not fit the G2D allocator (2 GiB) or the G2D hardware reports an error.

The method checks the arguments before it writes any data: if it returns FALSE because of invalid arguments or because it could not allocate memory the destination buffer is not changed. After an error of the G2D hardware the content of the destination buffer is undefined. The library cannot check that a non-null pointer is valid for the size passed with it: the caller guarantees that the buffers contain the image data of the given sizes.

The source and destination buffers must not overlap. The only accepted overlap is src == dst for equal source and destination sizes: the image is already in place and the method returns TRUE without touching the data.

By default the method resizes the whole image on the calling thread. Row-level parallelism is enabled with setMaxThreads, which is the only way to set the thread count, see Multithreading. The result does not depend on the number of threads and on the instruction set that the library selects at run time. The method is not thread-safe for one ImageResizer object, see Multithreading.

If the source and the destination sizes are equal the method just copies the image data: at scale 1.0 the cubic kernel degenerates to the weights {0, 1, 0, 0}, so the filtered result is byte identical to the source and the copy is the fastest way to produce it.

Example:

// Init image resizer.
rapidpixel::ImageResizer resizer;

// Init source and destination image buffers.
std::vector<uint8_t> src(640 * 480 * 3);
std::vector<uint8_t> dst(1920 * 1080 * 3);

// Resize on the calling thread.
if (!resizer.resize(src.data(), 640, 480, dst.data(), 1920, 1080))
{
    std::cout << "Resize failed" << std::endl;
}

// Allow 4 threads and resize again.
resizer.setMaxThreads(4);
if (!resizer.resize(src.data(), 640, 480, dst.data(), 1920, 1080))
{
    std::cout << "Resize failed" << std::endl;
}

setMaxThreads method

The setMaxThreads(…) method enables parallel resizing and sets an upper limit for the number of threads that resize(…) may use. Parallel resizing is disabled by default, so this method has to be called to make the resizer use more than one thread. Method declaration:

void setMaxThreads(int maxThreads);
Parameter Description
maxThreads Maximum number of threads. Value 1 (the default state of the object) keeps resizing single threaded. Values <= 0 mean “as many threads as OpenMP makes available”. The limit is never larger than omp_get_max_threads().

Returns: none. The setting belongs to the ImageResizer object and must be applied before resizing starts (the method is not thread-safe, it is not synchronised with resize calls that are already running). The method also starts the OpenMP worker threads, so the first resize does not pay for the team start-up.

Example:

rapidpixel::ImageResizer resizer;   // single threaded, nothing to configure

resizer.setMaxThreads(0);          // use every thread OpenMP offers
resizer.setMaxThreads(4);          // never use more than 4 threads
resizer.setMaxThreads(1);          // back to single threaded resizing

setMaxThreads(…) is the only way to set the thread count, exactly as in the FormatConverter library.

To keep some CPU cores free for other software, pass the number of cores the resizer is allowed to occupy:

#include <thread>

rapidpixel::ImageResizer resizer;

// Leave 2 cores of the machine free.
const int cores = static_cast<int>(std::thread::hardware_concurrency());
resizer.setMaxThreads(cores > 2 ? cores - 2 : 1);

getMaxThreads method

The getMaxThreads() method returns the thread limit that is in effect for the resizer. Method declaration:

int getMaxThreads() const;

Returns: the number of threads resize(…) may use at most, after setMaxThreads(…) is applied to the value provided by OpenMP. The value is 1 until setMaxThreads(…) is called and is always >= 1. The team size of a particular resize can be smaller, because it also depends on the destination image height, see Multithreading.

Example:

rapidpixel::ImageResizer resizer;
std::cout << resizer.getMaxThreads() << std::endl;   // 1

resizer.setMaxThreads(18);
std::cout << resizer.getMaxThreads() << std::endl;   // 18 on a 20 core machine

Multithreading

Parallel resizing is disabled by default. A freshly constructed ImageResizer resizes the whole image on the calling thread and does not create any OpenMP team. Call setMaxThreads to enable row-level parallelism. The thread control is identical to the one of the FormatConverter library, so both libraries are configured the same way in the same application.

resize(…) distributes the destination rows over the team with schedule(static), so each thread gets one contiguous band of rows and threads never share output bytes. The result does not depend on the number of threads: the same input always produces byte-identical output whether the resize runs on 1 thread or on 64.

The library never calls omp_set_num_threads(…) or omp_set_dynamic(…). The team size is passed to every parallel region with the OpenMP num_threads clause, which affects that region only. As a consequence:

  • the OpenMP configuration of your application is never modified by the library;
  • resize(…) may be called from several threads at the same time, but not through one ImageResizer object shared between threads, because the object caches the interpolation tables of the last used geometry. Give every thread its own ImageResizer instance;
  • calling resize(…) from inside your own #pragma omp parallel region is safe.

Number of threads

For every resize the team size is calculated as:

threads = min( getMaxThreads(),   // limit of the resizer
               dstHeight )        // cannot exceed the number of destination rows

Since getMaxThreads() returns 1 until setMaxThreads(…) is called, the default resizer always ends up with a single thread.

Table 2 - Team size on a 20 core machine after setMaxThreads(0).

Destination size Destination rows Threads used Threads used by default
64 x 8 8 8 1
320 x 240 240 20 1
1920 x 1080 1080 20 1
3840 x 2160 2160 20 1

Enabling and limiting the number of threads

Table 3 - Ways to control the thread count, from the widest scope to the narrowest.

Way Scope Description
Build without OpenMP Whole library If the compiler is invoked without OpenMP support the library builds and runs single threaded; setMaxThreads(…) is accepted but getMaxThreads() always returns 1.
OMP_NUM_THREADS environment variable Whole process Standard OpenMP setting. It defines the value returned by omp_get_max_threads(), which is the upper bound of what the resizer can request.
setMaxThreads(n) One ImageResizer Enables parallel resizing and sets a hard upper limit for that resizer object. n = 0 means all available threads, n = 1 means single threaded.

The limit is always at least 1 and never larger than omp_get_max_threads().

Example - a 20 core machine, 2 cores must stay free for other software:

#include <thread>
#include "ImageResizer.h"

rapidpixel::ImageResizer resizer;

const int cores = static_cast<int>(std::thread::hardware_concurrency());
resizer.setMaxThreads(cores > 2 ? cores - 2 : 1);

// 18
std::cout << resizer.getMaxThreads() << std::endl;

Example - ImageResizer and FormatConverter sharing one thread budget:

rapidpixel::ImageResizer    resizer;
rapidpixel::FormatConverter converter;

const int cores = static_cast<int>(std::thread::hardware_concurrency());
const int budget = cores > 2 ? cores - 2 : 1;

resizer.setMaxThreads(budget);
converter.setMaxThreads(budget);

Example - limiting the whole process from the command line:

OMP_NUM_THREADS=6 ./YourApplication

Performance

The library’s software implementation was compared against cv::resize(..., cv::INTER_CUBIC), which implements the same Keys cubic kernel (a = -0.75) with the same (dst + 0.5) * scale - 0.5 sample mapping.

The comparison is made against two OpenCV builds, because the difference between them is larger than the difference between OpenCV and this library:

  • OpenCV 5.0.0 official wheel, built with -O3 and Intel IPP 2026.0.0. cv::resize is dispatched to ippiResize here, which is the fastest resize implementation OpenCV can offer. This is the honest opponent and the numbers below should be read from this column.
  • OpenCV 4.6.0 distribution package (Ubuntu libopencv-dev). It is built without IPP, with -O2 and with hardening flags (-D_FORTIFY_SOURCE=3, -fstack-protector-strong, -fcf-protection, -fno-omit-frame-pointer), and falls back to OpenCV’s own SIMD kernels. Enabling IPP alone accounts for a 1.8x - 2.8x difference, so measuring against a distribution package overstates any advantage.

Both libraries were given the same number of threads (cv::setNumThreads(n) and setMaxThreads(n)) and were measured in separate processes, because letting the OpenMP team and the OpenCV thread pool run interleaved makes them fight for the same cores and distorts both results.

Test conditions: Intel Core i7-13700H (10 cores / 20 threads), Ubuntu 24.04, GCC 13.3, -O3 -march=native -funroll-loops -mssse3 -mavx2, BGR24 input, median of 51 runs.

Table 4 - Single thread, time per frame in microseconds.

Conversion ImageResizer OpenCV 5 + IPP Speedup OpenCV, no IPP Speedup
640x512 → 1920x1080 1418 2397 1.7x 5369 3.8x
1280x720 → 3840x2160 5197 7142 1.4x 17234 3.3x
320x240 → 1920x1080 1122 1790 1.6x 3306 2.9x
1920x1080 → 640x512 490 916 1.9x 2546 5.2x
3840x2160 → 1920x1080 3408 6068 1.8x 16506 4.8x
3840x2160 → 640x360 797 1255 1.6x 3182 4.0x
1920x1080 → 1920x1080 247 239 1.0x 217 0.9x

Table 5 - 4 threads, time per frame in microseconds.

Conversion ImageResizer OpenCV 5 + IPP Speedup OpenCV, no IPP Speedup
640x512 → 1920x1080 396 740 1.9x 1804 4.6x
1280x720 → 3840x2160 1478 2772 1.9x 5563 3.8x
320x240 → 1920x1080 341 786 2.3x 1182 3.5x
1920x1080 → 640x512 134 288 2.1x 1147 8.5x
3840x2160 → 1920x1080 1538 1946 1.3x 4755 3.1x
3840x2160 → 640x360 186 360 1.9x 953 5.1x
1920x1080 → 1920x1080 66 253 3.8x 267 4.0x

Against the strongest OpenCV build the library is roughly 1.4x - 2.3x faster. The margin comes from specialisation rather than from better vectorisation: this library only handles 8-bit 3-channel interleaved data in contiguous buffers with one interpolation mode, so it can keep the whole horizontal pass in 8-bit PMADDUBSW form and the vertical pass in int16, while cv::resize supports every depth, channel count, ROI stride and interpolation mode and pays for that generality. The same-size case is a plain copy in both libraries, so at one thread it is a tie and the difference at 4 threads only reflects how the copy is split.

Table 6 - Thread scaling of the library itself, time per frame in microseconds.

Conversion 1 thr 2 thr 4 thr 8 thr 20 thr Best speedup
640x512 → 1920x1080 1378 745 376 393 242 5.7x
1280x720 → 3840x2160 5082 2826 1418 1447 888 5.7x
1920x1080 → 640x512 533 285 125 145 86 6.2x
3840x2160 → 1920x1080 3428 2041 1185 853 539 6.4x

Scaling saturates around 6x on a 10 core machine because the filter is memory bandwidth bound rather than compute bound: at 4K the two passes move well over 100 MB per frame.

Accuracy versus OpenCV

The implementations use different fixed-point precision for the filter coefficients (6 fractional bits here, 11 in OpenCV), so the results differ by a fraction of an intensity level. The lower precision is part of the reason this library is faster: 6-bit weights fit in a byte and allow the 8-bit multiply-accumulate path. OpenCV’s own IPP and generic kernels differ from each other by up to 1 level, so the numbers below are the same against either.

Table 7 - Difference against cv::resize(..., cv::INTER_CUBIC), BGR24.

Conversion Max difference Mean difference PSNR
640x512 → 1920x1080 5 0.41 51.1 dB
1280x720 → 3840x2160 3 0.34 52.2 dB
320x240 → 1920x1080 5 0.54 49.1 dB
1920x1080 → 640x512 4 0.20 53.9 dB
3840x2160 → 1920x1080 1 0.65 50.0 dB
3840x2160 → 640x360 1 0.65 50.0 dB
1920x1080 → 1920x1080 0 0.00 exact

The output is also bit identical regardless of the thread count and of the SIMD backend: the x86 SSSE3/AVX2, the ARM64 NEON and the scalar kernels produce the same bytes for the same input.

Several libraries in one application

Different thread limits in different libraries do not conflict. The limit set with setMaxThreads(…) is a field of the library object, not a global setting, and it reaches OpenMP only through the num_threads clause of a particular parallel region. A num_threads clause applies to the region it is attached to and to nothing else, so an ImageResizer configured for 4 threads and a FormatConverter configured for 16 threads simply request different team sizes from the same shared thread pool:

rapidpixel::ImageResizer    resizer;
rapidpixel::FormatConverter converter;

resizer.setMaxThreads(4);     // resize(...) regions run on 4 threads
converter.setMaxThreads(16);  // convert(...) regions run on 16 threads

// 4 and 16, neither call changes the setting of the other library.
std::cout << resizer.getMaxThreads() << " " << converter.getMaxThreads();

This holds because neither library calls omp_set_num_threads(…) or omp_set_dynamic(…). Those functions write the process wide nthreads-var / dyn-var internal control variables, which is exactly what would make two libraries overwrite each other’s setting and would also silently change the OpenMP configuration of the host application.

Table 8 - What is shared between the libraries and what is not.

Item Shared Comment
m_maxThreads of the object No Private field, one per ImageResizer / FormatConverter object.
num_threads clause No Applies to a single parallel region only.
OpenMP worker thread pool Yes The runtime keeps one pool per thread. Teams are formed from it on demand, so different team sizes are fine.
omp_get_max_threads() Yes Upper bound for both libraries, controlled by OMP_NUM_THREADS or by the application. Neither library modifies it.

Two points still deserve attention:

  1. Oversubscription. The limits are independent, so they add up when the libraries work at the same time from different application threads. On a 20 core machine resizer.setMaxThreads(16) plus converter.setMaxThreads(16) may put 32 threads on 20 cores. This is a scheduling inefficiency, not a correctness problem, but for a pipeline that runs both libraries concurrently give them a shared budget:

    const int budget = static_cast<int>(std::thread::hardware_concurrency()) / 2;
    resizer.setMaxThreads(budget);
    converter.setMaxThreads(budget);
    

    When the libraries are used one after another in the same pipeline stage they never run at the same time and both can be given the full budget.

  2. One OpenMP runtime per process. Mixing several OpenMP runtimes in one binary (for example GCC libgomp together with LLVM libomp, or MSVC vcomp together with Intel libiomp5) gives each runtime its own thread pool and leads to oversubscription and, in some combinations, to crashes. This is a linking issue and not related to setMaxThreads(…): build all the libraries of the application with the same compiler and OpenMP implementation, which is what the CMake target OpenMP::OpenMP_CXX used by both libraries does.

Nested parallelism follows the usual OpenMP rules: if resize(…) is called from inside a #pragma omp parallel region of the application, the inner region is executed by a single thread unless the application enables nesting.

Build and connect to your project

Build stand alone

The repository does not contain sub-repositories. ImageResizer does not depend on other libraries of the repository family: OpenMP (supplied with the compiler) is optional and the G2D library is used only if it is found. Typical commands to build the library and the example:

cd ImageResizer
mkdir build
cd build
cmake ..
make

On Windows use cmake --build . --config Release instead of make. If ImageResizer is the top-level CMake project the main CMakeLists.txt file builds the library and the example.

By default the library is built in Release mode with aggressive compiler optimizations:

  • MSVC: /O2 /Ob3 /GL /Gy /LTCG
  • GCC/Clang: -O3 -funroll-loops -ffp-contract=off

No instruction set flag is applied to the whole library. On x86/x64 the AVX2 kernels are built in ImageResizerAvx2.cpp (-mavx2 for GCC/Clang, /arch:AVX2 for MSVC) and the SSSE3 kernels in ImageResizerSsse3.cpp (-mssse3 for GCC/Clang, no flag for MSVC). The library selects the best level that the CPU and the operating system support on the first resize(…) call that filters an image, see Portability. The built library runs on any x86-64 CPU. On ARM64 the NEON kernels are used and no extra flag is needed. The CMake option IMAGERESIZER_TARGET_ARCH sets -march= for the whole library: a library built with it runs only on CPUs that support the chosen architecture.

If you want to cross-build the library for i.MX, you need to execute the following commands:

source /opt/tdx-xwayland/7.3.0/environment-setup-cortexa55-tdx-linux
cd ImageResizer
mkdir build
cd build
cmake ..
make

To build and install the BSP, follow the instructions.

CMake options

Table 9 - CMake options of the repository. In the options below ${PARENT} is the prefix defined by the top-level project (empty if ImageResizer is the top-level project).

Option Default Description
${PARENT}_IMAGE_RESIZER ON Build the library.
${PARENT}_IMAGE_RESIZER_EXAMPLE ON (stand alone), OFF (included in other project) Build the example application.
${PARENT}_SUBMODULE_CACHE_OVERWRITE ON Forced rewriting of the options above in the CMake cache. The top-level project sets it to OFF when it includes ImageResizer as a sub-repository.
CMAKE_BUILD_TYPE Release (if not specified) Build type.
IMAGERESIZER_ENABLE_SIMD ON Build the SIMD kernels (AVX2 and SSSE3 on x86/x64, NEON on ARM64). If OFF only the portable C++ code is built.
IMAGERESIZER_TARGET_ARCH empty Value for -march= of GCC/Clang. Empty means portable code and the instruction set selected at run time.

The CMake file defines the following macros for the library (the user does not set them): IMAGERESIZER_NO_SIMD (the option IMAGERESIZER_ENABLE_SIMD is OFF), IMAGERESIZER_NO_SSSE3 and IMAGERESIZER_NO_AVX2 (the compiler does not accept the flags of the level or CPUID is not available; CMake prints a message), USE_G2D (the G2D header and library are found, the G2D implementation is built instead of the software implementation). The macros are private definitions of the library: ImageResizer.h does not use them and the programs which use the library do not define them.

If OpenMP is found the library links OpenMP::OpenMP_CXX (for example libgomp and pthread with GCC), and if the G2D header and library are found the library links the G2D library (libg2d). A program that links the library needs these libraries too; CMake adds them to targets that link ImageResizer.

Connect to your project

If you want to add ImageResizer to your CMake project as source code, you can do the following. ImageResizer has no dependencies on other repositories: nothing must be added to your project before it. For example, if your repository has the following structure:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp

Create folder 3rdparty in your repository and copy the folder of the library ImageResizer there (for example from the folder modules of the RapidPixel SDK). Structure of your repository:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    ImageResizer

Create CMakeLists.txt file in 3rdparty folder. CMakeLists.txt should contain:

cmake_minimum_required(VERSION 3.13)

################################################################################
## 3RD-PARTY
## dependencies for the project
################################################################################
project(3rdparty LANGUAGES CXX)

################################################################################
## SETTINGS
## basic 3rd-party settings before use
################################################################################
# To inherit the top-level architecture when the project is used as a submodule.
SET(PARENT ${PARENT}_YOUR_PROJECT_3RDPARTY)
# Disable self-overwriting of parameters inside included subdirectories.
SET(${PARENT}_SUBMODULE_CACHE_OVERWRITE OFF CACHE BOOL "" FORCE)

################################################################################
## CONFIGURATION
## 3rd-party submodules configuration
################################################################################
SET(${PARENT}_SUBMODULE_IMAGE_RESIZER                   ON  CACHE BOOL "" FORCE)
if (${PARENT}_SUBMODULE_IMAGE_RESIZER)
    SET(${PARENT}_IMAGE_RESIZER                         ON  CACHE BOOL "" FORCE)
    SET(${PARENT}_IMAGE_RESIZER_EXAMPLE                 OFF CACHE BOOL "" FORCE)
endif()

################################################################################
## INCLUDING SUBDIRECTORIES
## Adding subdirectories according to the 3rd-party configuration
################################################################################
if (${PARENT}_SUBMODULE_IMAGE_RESIZER)
    add_subdirectory(ImageResizer)
endif()

File 3rdparty/CMakeLists.txt adds folder ImageResizer to your project and excludes the example application from compiling (by default it is excluded when ImageResizer included as sub-repository). Your repository new structure will be:

CMakeLists.txt
src
    CMakeLists.txt
    yourLib.h
    yourLib.cpp
3rdparty
    CMakeLists.txt
    ImageResizer

Next you need include folder 3rdparty in main CMakeLists.txt file of your repository. Add string at the end of your main CMakeLists.txt:

add_subdirectory(3rdparty)

Next you have to include ImageResizer library in your src/CMakeLists.txt file:

target_link_libraries(${PROJECT_NAME} ImageResizer)

Done!

Portability

The library does not depend on the byte order of the host: it reads and writes only bytes of pixels and does not serialize any other data. The output of resize(…) is the same on all compilers and architectures that were built and run (MSVC 2022 on x64 and on x86 (32-bit); GCC 12 and 13 and Clang 15 and 18 on x86-64; GCC 13 and Clang 18 on ARM64): the same input gives byte identical output with every instruction set level and with any number of threads. The float calculations of the lookup tables must not use fused multiply-add: the library is built with -ffp-contract=off (GCC/Clang) and pragmas of MSVC and Clang in the source file.

The code for x86/x64 is built in three levels with identical results: AVX2, SSSE3 and portable C++. The kernels of every level are in a separate file that is compiled with the flags of its level only, the other files use the baseline instruction set of the target (SSE2 on x86-64). The library chooses the best level that the CPU and the operating system support once per process, on the first resize(…) call that filters an image: AVX2 needs the CPU flags AVX2 and SSSE3 and the operating system support of the YMM registers, SSSE3 needs the CPU flag SSSE3, otherwise the portable code is used. The level cannot be changed at run time. On ARM64 the NEON kernels are used (NEON is part of the ARM64 baseline); on other architectures the portable code is used. The levels can be switched off at build time, see CMake options. Only x86-64, x86 (32-bit, MSVC) and ARM64 targets were built and run.

Example

The example resizes a synthetic image from 640x512 to 1920x1080 and measures execution time:

#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <vector>
#include "ImageResizer.h"



namespace
{
/// Source image width, pixels.
constexpr int SRC_WIDTH{640};
/// Source image height, pixels.
constexpr int SRC_HEIGHT{512};
/// Destination image width, pixels.
constexpr int DST_WIDTH{1920};
/// Destination image height, pixels.
constexpr int DST_HEIGHT{1080};
/// Bytes per pixel of the image format (BGR24).
constexpr size_t BYTES_PER_PIXEL{3};
/// Maximum number of CPU cores the resizer is allowed to occupy.
constexpr int MAX_THREADS{4};
/// Number of timed resize runs. The median of the run times is reported.
constexpr int RUNS{21};
}



int main()
{
    std::cout << "ImageResizer v" << rapidpixel::ImageResizer::getVersion()
              << std::endl;

    // Create source image with deterministic pattern.
    std::vector<uint8_t> srcImg(static_cast<size_t>(SRC_WIDTH) * SRC_HEIGHT *
                                BYTES_PER_PIXEL);
    for (int y = 0; y < SRC_HEIGHT; ++y)
    {
        for (int x = 0; x < SRC_WIDTH; ++x)
        {
            const size_t idx = (static_cast<size_t>(y) * SRC_WIDTH +
                                static_cast<size_t>(x)) * BYTES_PER_PIXEL;
            srcImg[idx + 0] = static_cast<uint8_t>((x * 37 + y * 13) & 0xFF);
            srcImg[idx + 1] = static_cast<uint8_t>((x * 59 + y * 7) & 0xFF);
            srcImg[idx + 2] = static_cast<uint8_t>((x * 23 + y * 41) & 0xFF);
        }
    }

    // Create destination image buffer.
    std::vector<uint8_t> dstImg(static_cast<size_t>(DST_WIDTH) * DST_HEIGHT *
                                BYTES_PER_PIXEL);

    // Image resizer.
    rapidpixel::ImageResizer imageResizer;

    // Allow the resizer to occupy up to MAX_THREADS CPU cores. Without this
    // call the resize(...) method runs entirely on the calling thread.
    imageResizer.setMaxThreads(MAX_THREADS);
    std::cout << "Max threads: " << imageResizer.getMaxThreads() << std::endl;

    // Warmup run (includes one-time table build).
    const bool result = imageResizer.resize(srcImg.data(), SRC_WIDTH,
                                            SRC_HEIGHT, dstImg.data(),
                                            DST_WIDTH, DST_HEIGHT);
    std::cout << "Result: " << (result ? "OK" : "FAIL") << std::endl;
    if (!result)
    {
        return 1;
    }

    // Benchmark: run multiple times and report median. Every run is checked.
    std::vector<long long> times(RUNS);
    for (size_t i = 0; i < times.size(); ++i)
    {
        const auto begin = std::chrono::steady_clock::now();
        const bool resized = imageResizer.resize(srcImg.data(), SRC_WIDTH,
                                                 SRC_HEIGHT, dstImg.data(),
                                                 DST_WIDTH, DST_HEIGHT);
        const auto end = std::chrono::steady_clock::now();
        if (!resized)
        {
            std::cout << "Resize failed in run " << i << std::endl;
            return 1;
        }
        times[i] = std::chrono::duration_cast<std::chrono::microseconds>(
                end - begin).count();
    }
    std::sort(times.begin(), times.end());

    std::cout << "Resize time (median of " << RUNS << " runs): "
              << times[times.size() / 2] << " us" << std::endl;

    return 0;
}

Table of contents