Sub topic 3
Displaying and Saving Images
This chapter assumes basic Python, NumPy arrays, and OpenCV installation. You will learn how OpenCV shows an image in a window and writes an image to a file. The same image array can be displayed, saved, or passed to later processing steps.
Displaying an image in a window
OpenCV uses cv2.imshow to open a window and display an image:
cv2.imshow("Window title", image)The first argument is the window name. The second argument is the image array.
A common error is to call imshow without calling cv2.waitKey. The window may appear briefly and close immediately because the Python program reaches its end. waitKey(0) pauses until the user presses a key. A positive value waits for that many milliseconds.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
cv2.imshow("Image", img)
key = cv2.waitKey(0)
print("Key code:", key)
cv2.destroyAllWindows()cv2.destroyAllWindows() closes windows created by OpenCV. It is good practice to call it after the wait.
Displaying in different environments
cv2.imshow requires a graphical desktop. It may fail or do nothing on a server, in some containers, or in a notebook without GUI support. In those environments, save the image and inspect the file, or use the display tools provided by the notebook.
OpenCV stores a color image in blue-green-red, or BGR, order. OpenCV displays this order correctly. However, many Python plotting libraries expect red-green-blue, or RGB, order. If an OpenCV image looks red and blue swapped in another library, convert it first:
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)Saving an image to a file
Use cv2.imwrite to save an image:
success = cv2.imwrite("copy.png", img)
if not success:
raise IOError("Could not write copy.png")The filename extension usually determines the output format. For example, .png produces a PNG file and .jpg produces a JPEG file. JPEG uses lossy compression, so repeated saves can reduce image quality. PNG is often better for annotations, sharp edges, or images where exact pixel values matter.
The function returns True when OpenCV reports that the file was written successfully. It returns False when it cannot write the file, such as when the directory does not exist or permission is denied.
The format can change the stored data:
| Format | Typical use | Important behavior |
|---|---|---|
| PNG | Graphics and annotations | Lossless compression |
| JPEG | Photographs | Lossy compression and smaller files |
| BMP | Simple uncompressed output | Large files |
Displaying and saving a processed result
OpenCV drawing functions modify an array in place. After processing an image, display it, save it, or do both:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if not cv2.imwrite("photo-gray.png", gray):
raise IOError("Could not save photo-gray.png")
cv2.imshow("Grayscale image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()A grayscale image has one channel instead of three. OpenCV can display and save it without converting it back to color.
Exercise
Why can an OpenCV window close immediately after cv2.imshow?
Show answer
The program may finish before the window event loop can keep it open. Call cv2.waitKey, then call cv2.destroyAllWindows.