Working with Images: Resize and Crop in C++
In modern computer graphics and computer vision, the operations of resizing and cropping images are fundamental. Whether you are developing a photo processing application, a facial recognition system, or simply want to prepare images for a neural network, these functions are indispensable. In this article, we will take a detailed look at how to perform resize and crop in C++ using the powerful OpenCV library.
Why OpenCV?
OpenCV (Open Source Computer Vision Library) is the de facto standard for computer vision tasks. It is written in C/C++ and provides hundreds of optimized algorithms. For working with resize and crop, we only need a few functions, but their performance and flexibility make OpenCV an ideal choice.
You can install OpenCV via a package manager (for example, vcpkg install opencv or brew install opencv), or by building from source. Installation details are beyond the scope of this article, but it is assumed that you already have a project set up with the library linked.
Preparation: Loading an Image
Before changing anything, the image needs to be loaded. In OpenCV, this is done with the imread() function:
#include <opencv2/opencv.hpp>#include <iostream>
using namespace cv;using namespace std;
int main() { // Load the image Mat image = imread("input.jpg"); if (image.empty()) { cerr << "Error loading image!" << endl; return -1; } cout << "Original image size: " << image.cols << " x " << image.rows << endl; return 0;}The function returns an object of type Mat (matrix). If the file is not found or is corrupted, image.empty() will return true.
Resizing an Image in C++
The resize() function in OpenCV allows you to scale an image to arbitrary dimensions. It supports several interpolation methods that affect the quality of the result.
Resize Syntax
void resize(InputArray src, OutputArray dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR);- src — source image.
- dst — destination image.
- dsize — new size (width, height). Can be specified explicitly or calculated via
fxandfy. - fx — scale factor along the horizontal axis (if dsize = Size()).
- fy — scale factor along the vertical axis.
- interpolation — interpolation method. Main options:
INTER_NEAREST— nearest neighbor (fast, but with artifacts).INTER_LINEAR— bilinear (default, good balance).INTER_CUBIC— bicubic (slower, but higher quality).INTER_AREA— used when downscaling images (pixel area relation).
Example 1: Downscaling to a Fixed Size
Mat resized;Size newSize(300, 200); // Width 300, height 200resize(image, resized, newSize, 0, 0, INTER_AREA);imwrite("resized_fixed.jpg", resized);cout << "Size after resize: " << resized.cols << " x " << resized.rows << endl;Example 2: Scaling by 2x While Preserving Aspect Ratio
Mat scaled;resize(image, scaled, Size(), 0.5, 0.5, INTER_LINEAR);imwrite("scaled_half.jpg", scaled);If dsize = Size() is specified, the new dimensions are calculated using the formulas: dsiz