AttributeError: 'NoneType' object has no attribute 'shape'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: 'NoneType' object has no attribute 'shape' #

The Python "AttributeError: 'NoneType' object has no attribute 'shape'" occurs when we access the shape attribute on a None value, e.g. after passing an incorrect path to cv2.imread(). To solve the error, make sure to specify the correct path.

attributeerror nonetype object has no attribute shape

Here is a very simple example of how the error occurs.

main.py
import cv2 # 👇️ None img = cv2.imread('bad-path.png') # ⛔️ AttributeError: 'NoneType' object has no attribute 'shape' print(img.shape)

The imread method returns None when passed an incorrect path.

Trying to access the shape attribute on a None value causes the error.

You can get around the error by using an if statement to check if the variable is not None before accessing the shape attribute, but you'd still have to correct the path.

main.py
import cv2 img = cv2.imread('bad-path.webp') if img is not None: print('variable is not None') print(img.shape) else: print('variable is None')

The if block is only run if the img variable does not store a None value, otherwise the else block runs.

You can pass a path to the os.path.exists() method to check if the path exists.

main.py
import os # 👇️ check if path exists print(os.path.exists('thumbnail.webp')) # 👇️ returns the current working directory print(os.getcwd()) # 👉️ /home/borislav/Desktop/bobbyhadz_python

The os.getcwd() method returns the current working directory and can be used when constructing a path.

Conclusion #

The Python "AttributeError: 'NoneType' object has no attribute 'shape'" occurs when we access the shape attribute on a None value, e.g. after passing an incorrect path to cv2.imread(). To solve the error, make sure to specify the correct path.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.