How to Resize an Image with OpenCV
Tags: tutorial, programming, python, beginners
Published: 2023-02-03 18:17:45

---
title: How to Resize an Image with OpenCV
published: true
description: This tutorial will show you exactly how to resize an image using OpenCV and Python
canonical_url: https://www.jeremymorgan.com/tutorials/opencv/how-to-resize-image-opencv/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lmyu4rf9p06svfrjb0yw.jpg
tags: tutorial, programming, python, beginners
---

So you want to resize an image with OpenCV? You've found your answer. This tutorial will walk you through all the steps needed to do this. 

I will use Python in this example, but it's a similar process in many different languages. I often work with OpenCV in Go and C# as well. But let's stay on topic here. 

This will be a step by step guide to quickly resize and save an image using OpenCV. 


## Step 1: Create a Python Virtual Environment

Whenever I do anything with Python, I create a Virtual Environment. It's like a container for your Python application. It makes it portable and easy to manage dependencies. I'm using Linux for this, but it's the same commands in other operating systems. 

Open up a terminal window and choose the directory you'll be building your application under. I'm using a directory named "imageresizer" because I'm great at naming things creatively. 

Type in: 

```
python -m venv imageresizer
```

I'm going to name the Virtual Environment as "imageresizer". Again creativity. Let's activate the environment:

```
source imageresizer/bin/activate
```

Great! Your Virtual Environment is ready to use. 

!["How to Create a Python Virtual Environment"][0]


## Step 2: Select your Image

For this tutorial, I'm going to download a Photo by [Philip Jahn](https://unsplash.com/@pj_visual?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) from [Unsplash](https://unsplash.com/photos/RkU0A-yHQUo?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText). 

It's a beautiful photo and looks like this: 

!["How to Resize Images with OpenCV"][1]

And as you can see, it's quite large:

!["How to Resize Images with OpenCV"][2]


5304x7592 is excellent for printing. Not so much for the web. So how can we resize this thing without making it look funny?

We can use OpenCV! Keep reading.

## Step 3: Install OpenCV

Next, we'll need to install OpenCV in our Virtual Environment.

Type in: 

```
pip install opencv-python
```

And of course, I need to update pip. Just like it says, you type in:

```
pip install --upgrade pip
```

!["How to Resize Images with OpenCV"][3]

Ok, now OpenCV is installed. Let's build our script. 


## Step 4: Create a Python Script

Let's create the Python Script using OpenCV to resize the images. 

The first line imports our library. 

```Python
import cv2
```

Then we need to load the image we want to resize. 

```Python
image = cv2.imread('original.jpg')
```

Now let's get the original dimensions of the image:

```Python
height, width = image.shape[:2]
```

This uses the shape function and stores the width and height of the image. 


Now we need to set the output size of the image. This determines the size you want the *new* image to be.

```Python
output_size = (400, 400)
```

One thing to note, OpenCV will scale this. So the larger dimension of the image will be 400, and the smaller dimension will be scaled with a factor.

We need to calculate that scaling factor. Since the original dimensions are not square, resizing it to a square will distort the image. This will scale the smaller dimension appropriately. 

```Python
scaling_factor = min(output_size[0]/width, output_size[1]/height)
```

This divides the original image dimensions by the intended dimensions, then picks the smaller result for your scaling factor. 

Now, we'll resize the image. We'll pass in the original image, x and y scaling factors, and set interpolation to cv2.INTER_AREA:

```Python
resized_image = cv2.resize(image, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
```

Finally, we'll write the file. 

```Python
cv2.imwrite('output.jpg', resized_image)
```

Awesome. Let's run it!

## Step 5: Run the Script

At the prompt, type in:

```Python
python resize.py
```

If it's successful, you won't see any output. 

!["How to Resize Images with OpenCV"][4]

Now you can inspect your images. If you check the directory, you will see different file sizes, which tells you the image has changed:

!["How to Resize Images with OpenCV"][5]

Now, if we open the image, we can see it's 267x400! Quite a bit smaller. 

!["How to Resize Images with OpenCV"][6]

Congratulations! You just resized an image with OpenCV!

Here is the final code:

```Python
import cv2

# Load the image
image = cv2.imread('original.jpg')

# Get current image size
height, width = image.shape[:2]

# Set your output size 
output_size = (400, 400)

# Set the scaling factor
scaling_factor = min(output_size[0]/width, output_size[1]/height)

# Resize the image in memory
resized_image = cv2.resize(image, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)

# Write it to a new file
cv2.imwrite('output.jpg', resized_image)

```
## Extra Credit

We can make this script more useful. Let's take in a parameter for the image name and the size we'd like to make it. 

add the following line to the top:

```Python
import sys
```

Then, indent all the lines of code one tab. 

Then add: 

```Python
if len(sys.argv) > 1:
```

This statement says if arguments are passed to the command line, run the statements we just wrote to modify the image. 

and change:

```Python
image = cv2.imread('original.jpg')
```

to

```Python
image = cv2.imread(sys.argv[1])
```

Then at the bottom of the script, add the following:

```Python
else:
    print("You must provide a filename of the original image")

```

Now when you run the script, you can put in any image name you want: 

```
python resize.py original.jpg
```

If you don't enter a filename, the script will ask you to:

!["How to Resize Images with OpenCV"][7]

There you go! Have fun playing around with this! 

## Summary

In this tutorial, we learned how to resize images with OpenCV. It's pretty straightforward once you get the hang of it. It can get very complicated, however. 

Questions? Comments? [Yell at me!](http://bit.ly/JeremyCMorgan)

[0]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dy6idnowt56oxfbzxt35.jpg

[1]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e00ivot4a9qzpuecjdta.jpg

[2]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pjj66evj2gyby8p5klxy.jpg

[3]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79wxr157ermq9lem44r0.jpg

[4]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yn8buckfaxv0188g5jip.jpg

[5]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bdvoua5phj2s1su70h0x.jpg

[6]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c38ve5k94j9nro6phg3v.jpg

[7]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3tqg4oaknwc56udpb8k.jpg