Writing an Image

To write or save an image to a file, leverage the $cv2.imwrite()$ method which takes two arguments:

1. filename: to assign to the filed being saved
2. img: image variable to be written

Implementation

Generating a random image with numpy

import numpy as np 
import matplotlib.pyplot as plt 

# Generate a random image
random_image = np.random.randint(256, size=(600, 400, 3))

# display Random image
plt.imshow(random_image) 
writing_image_to_file
cv2.imwrite('opencv_image.jpg', random_image)
True

Similar to imread() configuration, there are several write configurations that come with OpenCV. Some of these configurations are:

  • cv2.IMWRITE_JPEG_QUALITY
  • cv2.IMWRITE_PNG_STRATEGY
  • cv2.IMWRITE_TIFF_YDPI

Depending on your use case, you may need a variation of write configuration. Check out the documentation for details on all write configuration.