In the previous post, you have known how to read the image files using the cv2.imread function. In this entire tutorial, I will show you how to use cv2 imwrite to write the image file to the disk with steps.
Steps to Save image file using cv2 imwrite
Step 1: Import the necessary libraries.
Here I am using the only OpenCV library. So import it using the import statement.
Step 2: Read the Image
Now before writing the image to the disk, let’s read an image file. To do so you have to use the cv2.imread() method. You have to just pass the path of the image as an argument.
Execute the line of code given below.
img = cv2.imread("flowers.jpg")
Here I am passing the image name “flowers.jpg”. And if print the image then you will see it as a NumPy array. Below is the image I am using.
In the next step, I will write or save the image in different colors and formats.
Step 3: Write the Image file using the cv2 imwrite()
There are certain examples of saving images using the cv2.imwrite() method. You will know each one.
Example 1: Saving the Image as it is with another name
If you want to save the image as it is with another name then you have to just pass the new filename and the image name. For example, I want to rename the filename to my-flowers.jpg then I will run the following lines of code.
Example 2: Convert the image to grayscale and save it
In this example, you will first convert the color image to grayscale and then save it. To convert an image to grayscale you have to use cv2.cvtColor() method.
Run the lines of code given below and see the output.
import cv2 img = cv2.imread("flowers.jpg") gray_image = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.imwrite("flowers-greyscale.jpg",gray_image)
Example 3: Change the type of the image file
OpenCV python module supports most of the image types. Suppose you want to change the type of the image. Here in this post, I am using the “jpg” format. Let’s change the type to png e.t.c. To do so you have to just change the filename with the “png” format and pass it to the imwrite() method.
import cv2 img = cv2.imread("flowers.jpg") cv2.imwrite("flowers.png",img)
You can see I have successfully changed the image type from jpg to png. You can also change to other types that OpenCV Supports.
OpenCV is the best image processing library to do computer vision complicated works. These are the steps to save or write the image file using the cv2 imwrite() method. Hope you have liked it. If you have any queries regarding this post then you can contact us for more information.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.