Python | cv2 imwrite() Method

In this tutorial, we will see how to save an image in your own system using python by using open-cv which exists as cv2 (computer vision) library.

You can use imwrite() method of cv2 library to save an image on your system. To use cv2 library, you need to import cv2 library using import statement.

Now let’s see the syntax and return value of imwrite() method, then we will move on to the examples.

Syntax

cv2.imwrite(path, image)

Parameters

You need to pass two parameters to imwrite() method. Parameters are:

  1. path: Location address where you want to save an image in your system in string form with including the filename.

    here two cases will be possible :

    i) if you want to save an image in the current working directory then we have to mention only the name of the image with their extension like .jpg,.png etc.

    ii) if you want to save an image at somewhere else in your system not in the current working directory then we have to give complete path, also known as, absolute path of the image.

  2. image: It is the image pixel matrix of that image, which you want to save in your system.

Return Value

It returns either True or False. Return True if the image is successfully saved otherwise return False.

cv2 imwrite() method Examples

Now Let’s see the Python code :

# import computer vision library(cv2) in this Program
import cv2

# import os library in this program
import os

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read an image
    image = cv2.imread(img_path)

    print("Before saving an image ,contents of directory shows :")

    # shows the contents of given directory
    print(os.listdir("C:\\Users\\user\\Desktop\\save image"))
    
    # mentioning absolute path 
    save_img_path = "C:\\Users\\user\\Desktop\\save image\\image1.jpg"
    
    # save an image at the given mention path
    cv2.imwrite(save_img_path,image)

    print("After saving an image ,contents of directory shows :")

    # shows the contents of given directory
    print(os.listdir("C:\\Users\\user\\Desktop\\save image"))

Output :

Before saving an image, contents of directory shows :
[]
After saving an image, contents of directory shows :
[‘image1.jpg’]

That’s all about cv2.imwrite() Method.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.