Master saving images to folders with CV2 Imwrite – top code examples included!

Table of content

  1. Introduction
  2. Overview of CV2 Imwrite
  3. Setting up the Environment
  4. Saving Images in Different Formats
  5. Adding Metadata to Images
  6. Advanced Techniques for Saving Images
  7. Working with Multiple Images
  8. Conclusion


When developing computer vision applications with Python and OpenCV, saving images to specific folders is often an important task. This can be particularly useful for organizing data for machine learning models or for batch-processing a large number of images.

Thankfully, the CV2 Imwrite function makes saving images to folders in Python quite easy. In this article, we will cover the basics of using CV2 Imwrite, including how to save images to specific file paths and how to name saved images dynamically. Additionally, we will provide top code examples to help you get started with efficiently saving images to folders using CV2 Imwrite.

Overview of CV2 Imwrite

CV2 Imwrite is a function used in the Python OpenCV library that is specifically designed to save and store image files. This function is particularly useful when working on image processing projects or computer vision projects.

Here are some key features of CV2 Imwrite:

  • Save images in various formats: This function can save images in a variety of file formats such as JPEG, PNG, BMP, TIFF, and WebP.
  • Flexible output options: With CV2 Imwrite, you can easily specify the file path and format when saving images to a directory or folder. You can also choose to save images with different quality levels and compression techniques.
  • Efficient image processing: CV2 Imwrite enables quick and efficient processing of large image files, even with limited resources.

Overall, CV2 Imwrite is an essential tool for anyone working on image processing or computer vision projects. By allowing you to save images in various formats, it enables you to store and organize your image files efficiently. Stay tuned for more information on how to use CV2 Imwrite in Python OpenCV.

Setting up the Environment

Before we dive into the specifics of saving images with CV2 Imwrite, let's first make sure we have the necessary tools and environment set up. Here's what you'll need:

1. Python 3.x

CV2 Imwrite is a Python package, which means you'll need to have Python 3.x installed on your machine. You can download the latest version of Python from the official website:

2. OpenCV

OpenCV is a popular computer vision library that includes CV2 Imwrite. You'll need to install OpenCV to use CV2 Imwrite. Here's how to install it:

  • On Windows, you can use the following command: pip install opencv-python
  • On macOS or Linux, you can use the following command: pip3 install opencv-python

3. An IDE

An IDE (Integrated Development Environment) is a software application that provides a programming environment for writing, editing, and testing code. There are several popular IDEs that support Python development, such as PyCharm, Visual Studio Code, and Sublime Text. Choose whichever IDE you feel most comfortable using.

4. A sample image

For the purposes of testing, you'll need a sample image to save to your computer. You can use any image you like, as long as it's in a file format that OpenCV supports (such as PNG or JPEG).

Once you have Python, OpenCV, an IDE, and a sample image set up, you're ready to start saving images with CV2 Imwrite!

Saving Images in Different Formats

CV2 Imwrite allows you to save images in different formats such as PNG, JPEG, BMP, and TIFF. Each format has its own advantages and disadvantages. Here is a brief overview of each format:

  • PNG (Portable Network Graphics): PNG is a popular format for images that have transparency. It uses lossless compression, which means that the image quality is not degraded when it is saved. However, it can result in larger file sizes compared to other formats.

  • JPEG (Joint Photographic Experts Group): JPEG is a widely used format for digital photography. It uses lossy compression, which means that some image data is discarded to reduce the file size. This can result in a loss of image quality, especially when the image is heavily compressed.

  • BMP (Bitmap): BMP is a simple format that stores images as uncompressed data. It is not widely used due to its large file sizes, but it can be useful for certain types of images such as icons.

  • TIFF (Tagged Image File Format): TIFF is a flexible format that can store multiple images and different types of data such as text, metadata, and color profiles. It uses lossless compression and is often used in professional photography and printing.

To save an image in a specific format using CV2 Imwrite, you simply need to specify the file extension in the file name. For example, to save an image as a PNG file, you would use the following code:

cv2.imwrite("image.png", image)

Similarly, to save an image as a JPEG file with a compression factor of 90, you would use the following code:

cv2.imwrite("image.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 90])

By specifying the appropriate file extension and options, you can save your images in the format that best suits your needs.

Adding Metadata to Images

Metadata is information that provides details about an image such as where and when it was taken, what camera or device was used, and other relevant information. can help users manage and organize their images with more precision. In this section, we will discuss how to add metadata to images using arguments in CV2 Imwrite.

CV2 Imwrite is a useful tool for saving images to folders. It provides several arguments that allow developers to customize the saved image's format, quality, and metadata. Here are some of the most commonly used arguments for :

  • ExifTags – ExifTags is a dictionary object that allows the user to add metadata tags to an image. Here are some examples of ExifTags:

    • ImageDescription – provides an image description.
    • Make – specifies the camera or device used to take the photo.
    • Model – specifies the model of the camera used to take the photo.
    • DateTime – specifies the date and time the image was taken.
    • GPSInfo – provides GPS location data for the image.
  • Format – specifies the format of the saved image. For example, JPEG, PNG, or BMP.

  • Quality – specifies the quality of the saved image. The quality value ranges from 0-100, with 100 being the highest quality.

By adding ExifTags to saved images, developers can provide users with relevant information about the image. This information can help users search and manage their images more efficiently. Here is an example code snippet that demonstrates how to add ExifTags to a saved image.

import cv2

img = cv2.imread('test_image.jpg')
exif_data = {'Make': 'MyCamera', 'Model': 'C100', 'ImageDescription':'Test Image'}
cv2.imwrite('saved_image.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), 90], ExifTags=exif_data)

In this example, we are adding ExifTags to a saved JPEG image. By passing the ExifTags parameter, we can specify the Make, Model, and ImageDescription values. We are also setting the image quality to 90.

In conclusion, using CV2 Imwrite can help developers provide users with more detailed information about an image. By using the ExifTags argument, developers can easily add relevant metadata to a saved image. With this tool, users can manage, organize, and search for their images more efficiently.

Advanced Techniques for Saving Images

While the basic process of saving images with CV2 Imwrite is straightforward, there are several advanced techniques that developers can use to further customize and optimize their image saving workflows. Here are a few examples:

  • Setting Image Compression Quality: By default, CV2 Imwrite uses a compression format that produces small file sizes, but may also result in a loss of image quality. However, developers can adjust the compression quality setting to achieve a balance between file size and image fidelity. The following line of code demonstrates how to set the compression quality to 90%:

    cv2.imwrite('example.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 90])
  • Choosing File Formats: In addition to the default JPEG compression format, CV2 Imwrite also supports several other file formats, such as PNG and BMP. Developers can specify the desired file format by passing the appropriate file extension as part of the filename parameter. Here is an example of saving an image as a PNG file:

    cv2.imwrite('example.png', img)
  • Creating Custom Naming Conventions: Developers can create custom naming conventions for their saved images by including variables or timestamps as part of the filename. For example, the following code generates a unique filename for every image based on the current timestamp:

    import time
    filename = 'example_{}.jpg'.format(int(time.time()))
    cv2.imwrite(filename, img)
  • Saving Multiple Images at Once: Finally, developers can save multiple images at once by using a loop to iterate over a list of images and saving each one individually. For example, the following code saves 10 images with sequentially numbered filenames:

    for i in range(10):
        filename = 'example_{}.jpg'.format(i)
        cv2.imwrite(filename, images[i])

By utilizing these advanced techniques, developers can further optimize their image saving workflows and create more customized and efficient applications.

Working with Multiple Images

When working on image processing tasks in Python, it is often necessary to handle multiple images at once. Here are some tips and code samples for using CV2 Imwrite:

Handling Image Files with Python

In order to work with multiple images, you'll first need to import the Python os library, which provides functions for interacting with the operating system. Specifically, you'll use os.listdir() to get a list of files in a directory and iterate over them to read and process each image.

Here's an example that reads each image file in a directory and saves a grayscale version:

import cv2
import os

folder_path = "/path/to/folder"
for file in os.listdir(folder_path):
    image_path = os.path.join(folder_path, file)
    image = cv2.imread(image_path)
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imwrite(os.path.join(folder_path, "gray_" + file), gray_image)

Batch Processing Images

If you have a large number of images to process, you may want to use Python's multiprocessing library to speed up the processing. This library allows you to run multiple processes in parallel, which can significantly reduce the processing time.

Here's an example that uses multiprocessing to apply a Gaussian blur to each image in a folder:

import cv2
import os
from multiprocessing import Pool

def process_image(file):
    image_path = os.path.join(folder_path, file)
    image = cv2.imread(image_path)
    blurred_image = cv2.GaussianBlur(image, (5, 5), 0)
    cv2.imwrite(os.path.join(folder_path, "blurred_" + file), blurred_image)

folder_path = "/path/to/folder"
files = os.listdir(folder_path)
with Pool() as pool:, files)


When in Python, it's important to use best practices for handling files and processing images efficiently. By using the tips and code samples provided here, you can save time and streamline your image processing workflow.


In , saving images to folders with CV2 Imwrite is an essential part of any computer vision project. By using this method, you can easily organize and store image data for later use. In this article, we have discussed the basics of CV2 Imwrite and explored some top code examples to help you get started with image saving in Python.

Remember to always pay attention to the file format you are saving the image in and make sure your file extensions match up. The file format can affect the quality of your images, so it's important to choose the right one for your needs.

We hope this article has provided you with a solid understanding of how to use CV2 Imwrite to save images. If you have any further questions or comments, feel free to leave them in the comments section below. Happy coding!

As a developer, I have experience in full-stack web application development, and I'm passionate about utilizing innovative design strategies and cutting-edge technologies to develop distributed web applications and services. My areas of interest extend to IoT, Blockchain, Cloud, and Virtualization technologies, and I have a proficiency in building efficient Cloud Native Big Data applications. Throughout my academic projects and industry experiences, I have worked with various programming languages such as Go, Python, Ruby, and Elixir/Erlang. My diverse skillset allows me to approach problems from different angles and implement effective solutions. Above all, I value the opportunity to learn and grow in a dynamic environment. I believe that the eagerness to learn is crucial in developing oneself, and I strive to work with the best in order to bring out the best in myself.
Posts created 294

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top