Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 54 ยท Getting Started

Reading, Showing and Saving Images

Load images with cv2.imread and its flags, show them with imshow and waitKey, save with imwrite, and avoid the None-on-bad-path trap. Includes headless options.

Real programs start with a file and end with a file. OpenCV has three functions for that: cv2.imread loads an image into an array, cv2.imshow displays it in a window, and cv2.imwrite saves an array to disk. They look trivial, but each hides a behavior that trips up beginners: imread returns None instead of raising an error, imshow needs waitKey, and imwrite decides the format from the file extension.

All the cv2 code here runs on your computer (see Installing OpenCV), so it is shown read-only. The live TryIts use a tiny text image format to show the same ideas: write an array to a file-like string, read it back, and handle a missing file.

Reading with imread

Python
import cv2

img = cv2.imread("photo.jpg")                        # default: 3-channel BGR
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)  # 2D array
raw = cv2.imread("logo.png", cv2.IMREAD_UNCHANGED)   # keeps alpha if present

if img is None:
    raise FileNotFoundError("could not read photo.jpg")

The second argument is a flag:

Flag Result
cv2.IMREAD_COLOR (default) Always 3 channels, BGR, alpha dropped
cv2.IMREAD_GRAYSCALE One channel, shape (H, W)
cv2.IMREAD_UNCHANGED The file as stored, including alpha or 16-bit depth

When the path is wrong, the file is missing, or the format is unsupported, imread does not raise an exception. It quietly returns None. The error only appears later, as a confusing message such as 'NoneType' object has no attribute 'shape'. Always check if img is None right after loading.

Relative paths are resolved from the current working directory, not from the script's folder. If an image "obviously exists" but loads as None, print os.getcwd() and check the path. Also be careful with non-ASCII characters in paths on Windows; one reliable workaround is to read the bytes yourself and decode them:

Python
import numpy as np, cv2

data = np.fromfile("fotos/cafรฉ.jpg", dtype=np.uint8)
img = cv2.imdecode(data, cv2.IMREAD_COLOR)

Showing with imshow

Python
cv2.imshow("My photo", img)   # window title, array
key = cv2.waitKey(0)          # wait forever for a key press
cv2.destroyAllWindows()

imshow only queues the picture. The window is drawn and kept responsive by waitKey, which waits that many milliseconds for a key (0 means forever) and returns the key code, or -1 if none was pressed. Without waitKey the window flashes and vanishes, or never appears. In video loops you call waitKey(1) once per frame.

The show-and-wait pattern

imshow Queue the picture for a window.
waitKey Draw it and wait for a key.
destroyAllWindows Close everything when done.

No waitKey, no window.

1 / 2

Saving with imwrite

Python
ok = cv2.imwrite("out.png", img)       # format chosen by the extension
cv2.imwrite("out.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 90])
print(ok)                              # True or False

imwrite returns True on success and False if it could not write (for example, the folder does not exist). PNG is lossless; JPEG is lossy and takes a quality from 0 to 100. Saving to JPEG repeatedly degrades the picture each time, so keep a PNG while you work.

Headless machines and notebooks

On a server, in Docker, or with opencv-python-headless, imshow fails or has no display. Choose one of these instead:

Python
# 1) Save the result and open the file yourself.
cv2.imwrite("debug.png", img)

# 2) In a Jupyter notebook, use matplotlib (convert BGR to RGB first!).
import matplotlib.pyplot as plt
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.show()

The BGR to RGB conversion matters because matplotlib expects red first; skipping it gives blue-tinted faces. Color Spaces explains why.

A stand-in: PGM text images

Real image codecs (JPEG, PNG) are far too big to rebuild here. But the PGM format is a tiny text format for grayscale images, and it shows the same round trip: array to file text, and file text back to array, including the None failure style. The "files" below are strings in a dictionary named disk, standing in for a real folder.

Python imwrite and imread, in miniature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The file text begins with a magic word P2, then width and height, the maximum value 255, then the rows of numbers. Reading it back reshapes a flat list of numbers into (height, width), which is conceptually what a real decoder does after decompression. The last line shows the dangerous bit: a missing file gives None, not an error.

A stand-in: showing an image as text

Without a window, the simplest "display" is text. This helper maps brightness to a character ramp, so you can inspect any small array right on the page. We will use it again in later lessons.

Python A text-mode imshow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The negative is just 255 - disc, because uint8 values run from 0 to 255. The text-mode display is a stand-in for cv2.imshow; the array math is real NumPy that works the same on any OpenCV image.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does cv2.imread return if the file path is wrong?

    imread fails silently by returning None, so you should check for it immediately.
  2. 2. What is the job of cv2.waitKey in an imshow program?

    Windows are updated inside waitKey. Without it the window may never appear.
  3. 3. Which flag loads an image as a single-channel grayscale array?

    IMREAD_GRAYSCALE returns shape (H, W).
  4. 4. How does imwrite decide whether to write PNG or JPEG?

    The extension in the filename (.png, .jpg) selects the encoder.

Summary

  • cv2.imread(path, flag) returns an array, or None when it fails; always check for None.
  • imshow needs waitKey to draw the window; use imwrite or matplotlib on headless machines.
  • imwrite picks the format from the extension and returns True or False.
  • The PGM and text-display stand-ins show the array-to-file round trip; real cv2 code stays read-only here.

Next up: Color Spaces: BGR, RGB, Gray and HSV.