OpenCV
image processing
error handling
debugging
resize function

error -215 ssize.width 0 ssize.height 0 in function resize

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

The OpenCV error (-215:Assertion failed) !ssize.empty() in function 'resize' or (-215) ssize.width > 0 && ssize.height > 0 in function resize occurs when cv2.resize() receives an empty or None image. This means the image was not loaded successfully, or a previous operation produced an empty result. The error is an assertion failure, not a runtime exception, so it indicates a programming mistake rather than an expected condition.

The Error

python
1import cv2
2
3img = cv2.imread('nonexistent_file.jpg')
4resized = cv2.resize(img, (300, 200))
5# error: (-215:Assertion failed) !ssize.empty() in function 'resize'

Root Cause

cv2.imread() does not raise an exception when a file is missing or unreadable — it silently returns None:

python
img = cv2.imread('wrong_path.jpg')
print(img)       # None
print(type(img)) # <class 'NoneType'>

Passing None to cv2.resize() triggers the assertion failure.

Fix 1: Check if Image Loaded

Always verify the image is not None before processing:

python
1import cv2
2
3img = cv2.imread('photo.jpg')
4
5if img is None:
6    print("Error: Could not load image")
7else:
8    resized = cv2.resize(img, (300, 200))
9    cv2.imshow('Resized', resized)
10    cv2.waitKey(0)

Fix 2: Verify the File Path

The most common cause is an incorrect file path:

python
1import os
2
3path = 'images/photo.jpg'
4
5# Check if file exists
6if not os.path.exists(path):
7    print(f"File not found: {path}")
8    print(f"Current directory: {os.getcwd()}")
9    print(f"Files in directory: {os.listdir('images/')}")
10else:
11    img = cv2.imread(path)

Common path issues:

  • Relative paths resolve from the working directory, not the script location
  • Backslashes on Windows need escaping: 'C:\\Users\\photo.jpg' or r'C:\Users\photo.jpg'
  • File extensions are case-sensitive on Linux: photo.JPG vs photo.jpg

Fix 3: Check for Empty Image After Operations

Other OpenCV operations can also produce empty images:

python
1img = cv2.imread('photo.jpg')
2
3# Video capture might return empty frames
4cap = cv2.VideoCapture(0)
5ret, frame = cap.read()
6if not ret or frame is None:
7    print("Failed to capture frame")
8
9# Crop can produce empty image with wrong coordinates
10crop = img[500:400, 0:100]  # start > end = empty!
11print(crop.shape)  # (0, 100, 3) — empty
12
13# Check before resize
14if crop.size == 0:
15    print("Crop is empty")

Fix 4: Handle Video Streams

When processing video, frames may be empty at the end of the file or on capture failure:

python
1cap = cv2.VideoCapture('video.mp4')
2
3while True:
4    ret, frame = cap.read()
5    if not ret:
6        break  # end of video or read failure
7
8    # Safe to resize
9    resized = cv2.resize(frame, (640, 480))
10    cv2.imshow('Video', resized)
11    if cv2.waitKey(1) & 0xFF == ord('q'):
12        break
13
14cap.release()

Fix 5: Validate Resize Dimensions

The target dimensions must be positive integers:

python
1# WRONG: zero or negative dimensions
2resized = cv2.resize(img, (0, 200))     # Error
3resized = cv2.resize(img, (-100, 200))  # Error
4
5# WRONG: float dimensions
6resized = cv2.resize(img, (300.5, 200.5))  # Error
7
8# CORRECT: positive integers
9resized = cv2.resize(img, (300, 200))
10
11# Using scale factor instead
12resized = cv2.resize(img, None, fx=0.5, fy=0.5)  # half size

Defensive Helper Function

python
1def safe_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
2    """Resize image safely with aspect ratio preservation."""
3    if image is None or image.size == 0:
4        raise ValueError("Input image is empty or None")
5
6    h, w = image.shape[:2]
7
8    if width is None and height is None:
9        return image
10
11    if width is None:
12        ratio = height / float(h)
13        dim = (int(w * ratio), height)
14    elif height is None:
15        ratio = width / float(w)
16        dim = (width, int(h * ratio))
17    else:
18        dim = (width, height)
19
20    if dim[0] <= 0 or dim[1] <= 0:
21        raise ValueError(f"Invalid dimensions: {dim}")
22
23    return cv2.resize(image, dim, interpolation=inter)
24
25# Usage
26try:
27    resized = safe_resize(img, width=300)
28except ValueError as e:
29    print(f"Resize failed: {e}")

Common Pitfalls

  • Silent failure of imread: cv2.imread() returns None on failure without raising an exception. Always check the return value.
  • Working directory: When running from an IDE, the working directory may differ from the script's directory. Use os.path.abspath() or pathlib.Path(__file__).parent for reliable paths.
  • Unsupported formats: OpenCV may fail to read certain image formats if codecs are not installed. Check with cv2.haveImageReader('file.webp').
  • Grayscale loading: cv2.imread('img.jpg', cv2.IMREAD_GRAYSCALE) returns a 2D array. Some resize operations expect 3D arrays. Check img.ndim.
  • URL images: cv2.imread() does not support URLs. Download the image first with urllib or requests, then decode with cv2.imdecode().
  • Permission errors: On some systems, OpenCV silently returns None for files it cannot read due to permissions.

Summary

  • The error means cv2.resize() received an empty or None image
  • Always check if img is None after cv2.imread() — it does not raise exceptions
  • Verify file paths with os.path.exists() before loading
  • For video, check the ret flag from cap.read() before processing frames
  • Ensure resize dimensions are positive integers, not zero, negative, or float

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.