How to Save OpenCV Image to a File in Python

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.


First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3


In this tutorial, I will show you how to save OpenCV output image to a file.


Python: cv2.imwrite(filename, img[, params]) → retval

Saves an image to a specified file.


  • filename – Name of the file.
  • image – Image to be saved.
  • params
    • Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, …. The following parameters are currently supported:
      • For JPEG, it can be a quality (CV_IMWRITE_JPEG_QUALITY) from 0 to 100 (the higher is the better). Default value is 95.
      • For PNG, it can be the compression level (CV_IMWRITE_PNG_COMPRESSION) from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3.
      • For PPM, PGM, or PBM, it can be a binary format flag (CV_IMWRITE_PXM_BINARY), 0 or 1. Default value is 1.


  • Load Image using cv2.imread()
  • Display Image using cv2.imshow()
  • Save the output in an image file using cv2.imwrite()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2
import numpy as np

def main():
    imgpath = "Hanif.jpg"
    img = cv2.imread(imgpath)

    #display the image
    cv2.imshow('Hanif_Life2Coding', img)

    outpath = "Hanif_Save.jpg"
    #save the image
    cv2.imwrite(outpath, img)

    #destroy a certain window

if __name__ == "__main__":


2 How to Save OpenCV Image to a File in Python

life2coding_icon [] How to Save OpenCV Image to a File in Python

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.