Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to resize or rescale in OpenCV

📅 2014-Sep-03 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ iplimage, mat, opencv, rescale, resize ⬩ 📚 Archive

An image cannot be resized or rescaled inplace in OpenCV. You will need to create another image with the new size or scale and apply a resize operation.

Resizing or rescaling a Mat is somewhat easier than dealing with a IplImage. The code below illustrates these operations on both data types:

const int kNewWidth = 200;
const int kNewHeight = 400;
const float kRescaleFactor = 0.75;

/**
 * Resize mat
 */

Mat mat; // Input
Mat new_mat;
resize(mat, new_mat, cvSize(kNewWidth, kNewHeight));

/**
 * Rescale mat
 */

Mat mat; // Input
Mat new_mat;
resize(mat, new_mat, cvSize(0, 0), kScaleFactor, kScaleFactor);

/**
 * Resize IplImage
 */

IplImage* img; // Input
IplImage* new_img = cvCreateImage(cvSize(kNewWidth, kNewHeight), img->depth, img->nChannels);
cvResize(img, new_img);

/**
 * Rescale IplImage
 */

IplImage* img; // Input
const int new_width = (int) ((float) img->width * kRescaleFactor);
const int new_height = (int) ((float) img->height * kRescaleFactor);
IplImage* new_img = cvCreateImage(cvSize(new_width, new_height), img->depth, img->nChannels);
cvResize(img, new_img);

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧