Sub topic 2
Reading an Image and Checking That It Loaded
This chapter covers cv2.imread: how to call it, how it fails, and how to confirm that the array it returns is what you expect. It assumes you can write basic Python functions, have installed OpenCV with pip install opencv-python numpy, know how to index a NumPy array, and understand pixels, width, height, and color channels.
What cv2.imread does
cv2.imread(path, flags) reads an image file from disk, decodes it, and returns a NumPy array. The format (JPEG, PNG, BMP, TIFF, and others) is detected from the file contents, not from the extension.
The returned array has three properties you will use constantly:
shapeis(height, width, channels)for a color image. Rows come first.dtypeisuint8, so each value is an integer from 0 to 255.- Channel order is blue, green, red (BGR), not the RGB order most other libraries use.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
print(img.shape) # (height, width, 3)
print(img.dtype) # uint8
h, w = img.shape[:2]
b, g, r = img[0, 0] # channel order is blue, green, redThe pixel at img[0, 0] is the top-left corner. Indexing uses img[row, column], which is img[y, x].
The silent failure: imread returns None
Most Python file functions raise an exception when a file is missing. cv2.imread does not. When it cannot load the file, it returns None and prints nothing, or at most a warning from the underlying library.
This causes confusing errors later. If you skip the check, the first use of the result fails far from the real problem:
import cv2
img = cv2.imread("missing.jpg")
print(img.shape) # AttributeError: 'NoneType' object has no attribute 'shape'The error message mentions NoneType, but the real cause is the failed load. Other functions fail differently. cv2.imshow and cv2.resize raise cv2.error with messages such as !_src.empty(), which also point away from the cause.
Always test the result immediately after reading:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")Use is None, not if not img. Truth-testing a NumPy array with more than one element raises a ValueError.
Why a load fails
Several causes produce the same None result. Check them in this order.
- Wrong path. A relative path is resolved against the process's current working directory, not the script's folder. Running the script from a different directory breaks it.
- Typo or wrong extension.
photo.jpegandphoto.jpgare different files. - Missing permissions. The process may not be allowed to read the file.
- Corrupt or truncated file. The file exists but cannot be decoded.
- Unsupported format. OpenCV's build may lack a codec, for example for some WebP or HEIC files.
- Non-ASCII characters in the path. On some platforms, especially Windows,
imreadfails on paths such asC:\Users\José\photo.jpg.
To rule out path problems, resolve the path against the script's location and check that the file exists before calling imread:
from pathlib import Path
import cv2
path = Path(__file__).parent / "photo.jpg"
print("Looking for:", path.resolve())
if not path.is_file():
raise FileNotFoundError(f"No such file: {path}")
img = cv2.imread(str(path))
if img is None:
raise ValueError(f"File exists but could not be decoded: {path}")Separating the two checks tells you whether the file is missing or unreadable. Note that __file__ is not defined in an interactive session or notebook. In those, use Path.cwd() instead of Path(__file__).parent.
Handling non-ASCII paths
If the path contains non-ASCII characters and imread returns None for a file that exists, read the bytes with NumPy and decode them in memory with cv2.imdecode:
from pathlib import Path
import cv2
import numpy as np
def read_image(path, flags=cv2.IMREAD_COLOR):
data = np.fromfile(str(path), dtype=np.uint8)
if data.size == 0:
return None
return cv2.imdecode(data, flags)
img = read_image(Path("photos") / "café.jpg")
if img is None:
raise ValueError("Could not read the image")cv2.imdecode also returns None when it cannot decode the data, so the same is None check applies.
Reading flags
The second argument controls how the file is converted on load. The three common values are:
| Flag | Value | Result |
|---|---|---|
| `cv2.IMREAD_COLOR` | 1 | 3-channel BGR image. This is the default. Any alpha channel is dropped. |
| `cv2.IMREAD_GRAYSCALE` | 0 | 2D array with shape `(height, width)`. |
| `cv2.IMREAD_UNCHANGED` | -1 | Keeps the file's own channels and bit depth, including alpha. |
The flag changes the shape you get back:
import cv2
color = cv2.imread("logo.png") # (h, w, 3)
gray = cv2.imread("logo.png", cv2.IMREAD_GRAYSCALE) # (h, w)
full = cv2.imread("logo.png", cv2.IMREAD_UNCHANGED) # (h, w, 4) if the PNG has alpha
for name, image in [("color", color), ("gray", gray), ("full", full)]:
if image is None:
raise FileNotFoundError("Could not read logo.png")
print(name, image.shape, image.dtype)With IMREAD_UNCHANGED, the result depends on the file:
- A grayscale PNG gives a 2D array.
- A PNG with transparency gives four channels in B, G, R, A order.
- A 16-bit PNG or TIFF gives
uint16, notuint8.
Code that assumes shape has three entries breaks on grayscale input. When you read with IMREAD_UNCHANGED, check img.ndim before unpacking the shape.
import cv2
img = cv2.imread("logo.png", cv2.IMREAD_UNCHANGED)
if img is None:
raise FileNotFoundError("Could not read logo.png")
if img.ndim == 2:
print("Grayscale image")
else:
h, w, channels = img.shape
print(f"{w}x{h} with {channels} channels")EXIF orientation
Phone photos often store the picture sideways and record a rotation in EXIF metadata. Recent OpenCV versions apply that rotation when they read the file, so the array looks upright. You can turn this off with cv2.IMREAD_IGNORE_ORIENTATION. If images from another tool appear rotated compared with what OpenCV shows, this metadata is the likely cause. Behavior differs in older OpenCV versions, so check cv2.__version__ when results look wrong.
A reusable loader with validation
Repeating the same checks in every script is error-prone. Put them in one function:
from pathlib import Path
import cv2
def load_image(path, flags=cv2.IMREAD_COLOR):
path = Path(path)
if not path.is_file():
raise FileNotFoundError(f"No such file: {path.resolve()}")
img = cv2.imread(str(path), flags)
if img is None:
raise ValueError(f"Could not decode image: {path}")
if img.size == 0:
raise ValueError(f"Image is empty: {path}")
return img
img = load_image("photo.jpg")
h, w = img.shape[:2]
print(f"Loaded {w}x{h}, dtype={img.dtype}, channels={img.shape[2] if img.ndim == 3 else 1}")The function raises specific exceptions, so a caller can tell a missing file from a bad one. A script that processes many files can catch these exceptions per file and continue with the rest.
Memory and size
A decoded image takes height * width * channels bytes for uint8, regardless of how small the file is on disk. A 4000 by 3000 color photo is about 36 MB in memory (4000 × 3000 × 3 bytes). The JPEG file might be only 3 MB. Loading thousands of full-size images into a list can exhaust memory. Process one image at a time, or resize each one right after loading.
OpenCV also offers reduced-size decoding flags such as cv2.IMREAD_REDUCED_COLOR_2, which decodes at half size in each dimension. For JPEG this is faster than decoding fully and then shrinking.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `AttributeError: 'NoneType' object has no attribute 'shape'` | `imread` failed and the check was skipped. | Add the `is None` check right after the read. |
| `cv2.error` with `!_src.empty()` | A `None` or empty image was passed to a function. | Check the load result. |
| Colors look wrong in Matplotlib | Matplotlib expects RGB, OpenCV gives BGR. | Convert with `cv2.cvtColor`, covered in a later chapter. |
| Unpacking `h, w, c = img.shape` raises `ValueError` | The image is grayscale, so `shape` has two entries. | Use `img.shape[:2]` or check `img.ndim`. |
| Alpha channel missing | The default flag drops it. | Use `cv2.IMREAD_UNCHANGED`. |
Exercises
Exercise
A script calls img = cv2.imread("data/cat.jpg") and then img.shape. It crashes with "AttributeError: 'NoneType' object has no attribute 'shape'", although cat.jpg is in the data folder next to the script. Name two likely causes and one check for each.
Show answer
First, the working directory may differ from the script's folder, so the relative path points elsewhere. Print Path("data/cat.jpg").resolve() or build the path from Path(_file).parent and test isfile(). Second, the file may be corrupt or in an unsupported format. If is_file() is True but imread still returns None, try opening the file in an image viewer or re-saving it as PNG.
Exercise
You read logo.png with cv2.IMREAD_UNCHANGED and run h, w, c = img.shape. For one file this raises "ValueError: not enough values to unpack". What is the cause, and how do you make the code safe?
Show answer
That file is a grayscale PNG, so img has shape (height, width) with only two entries. Use h, w = img.shape[:2], and compute channels as img.shape[2] if img.ndim == 3 else 1.
Exercise
Why is "if not img:" the wrong way to test whether imread succeeded, and what should you write instead?
Show answer
When imread succeeds, img is a NumPy array with many elements, and truth-testing it raises a ValueError about ambiguous truth values. Write "if img is None:" instead.