How to Write Images to a Folder in Python

In this tutorial, we will learn how to write images to a folder in Python. We will use two important Python libraries: OpenCV and os. OpenCV handles the image operations while the os library helps us to create a new directory for storing our images.

Step 1: Import the required libraries

For this script, we need opencv and os libraries. You can install OpenCV using pip:

Then, import these libraries in your Python script:

Step 2: Create a new folder

We will use the os library to create a new directory, where we will save our images.

Step 3: Read and Save the Image

We’ll now read an image using the imread() function of OpenCV, and then write this image to our created folder using the imwrite() function.

Step 4: Optional Step – Display the Image

If we want to verify if the image has been successfully saved or not, we can display the read image using the imshow function of OpenCV.

This will display the image in a new window. You can close this window by pressing any key.

The Full Code

Conclusion

By following these simple steps, you can easily write images to a new folder using Python. Python’s os and OpenCV libraries make this task straightforward and efficient. Happy coding!