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:
1 |
pip install opencv-python |
Then, import these libraries in your Python script:
1 2 |
import cv2 import os |
Step 2: Create a new folder
We will use the os library to create a new directory, where we will save our images.
1 2 |
folder = 'Images' os.mkdir(folder) |
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.
1 2 |
img = cv2.imread('image.jpg') # Read the image cv2.imwrite(os.path.join(folder , 'new_image.jpg'), img) |
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.
1 2 |
cv2.imshow('image', img) cv2.waitKey(0) |
This will display the image in a new window. You can close this window by pressing any key.
The Full Code
1 2 3 4 5 6 7 8 9 10 11 |
import cv2 import os folder = 'Images' os.mkdir(folder) img = cv2.imread('image.jpg') # Read the image cv2.imwrite(os.path.join(folder , 'new_image.jpg'), img) cv2.imshow('image', img) cv2.waitKey(0) |
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!