Borislav Hadzhiev
Wed Apr 20 2022·1 min read
Photo by Joshua Earle
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.
Here is a very simple example of how the error occurs.
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.
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 ran 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.
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.