Fix AttributeError: 'NoneType' Object Has No Attribute 'Shape'
NumPy is a popular tool for computing numbers involving matrices, arrays, and math functions. The shape attribute of a NumPy array returns a tuple showing the array's dimensions. And when it comes to reshaping and manipulating NumPy arrays, the attribute is crucial.
Below is how the shape
attribute function:
import numpy as np
arr = np.array([[5, 1], [16, 33]])
print(arr.shape)
Output:
(2, 2)
The shape attribute is also important in pandas or OpenCV.
Here is how the shape attribute is used in OpenCV:
import cv2
img = cv2.imread(r'C:\Users\ADMIN.DESKTOP-KB78BPH\Desktop\New folder
(2)\2.jpg')
print(img.shape)
The output is:
(1280, 1920, 3)
As observed, the program executes and returns the shape of (1280, 1920, 3). The provided detail is important as it allows presents the structure of the array and hence makes it possible to perform operations on it.
However, sometimes you can try to access the shape attribute but end up prompted with the error message AttributeError: NoneType
object has no attribute shape
. The error occurs when NumPy has been assigned to the value None or has not been initialized at all. It thus indicates that the array is not properly defined, and hence you cannot use it to perform operations.
In this article, you learn about working solutions for resolving the error so that you can complete development using the data processing libraries such as Pandas and NumPy.
We first cover the solutions in summary and then later wards in detail. Let's dive in.
Too Long? Here Is a Quick Solution
- Initialize an array with valid values, or ensure functions do not return
None
. - Confirm that the image or video path is accurate since an incorrect path prompts the error. Also, provide a path that does not contain Unicode characters since OpenCV does not support such. Alternatively, change the image or video location.
- Add assert after you load the image/frame. Another option is to use try/except to handle the error.
- If you are using images created using artificial intelligence and saved them but faced the error when you tried opening the image, note that you need to add
dtype=np.uint8
so that you can save images created using artificial intelligence. Further, ensure that the camera on your device is not open to another program. If so, close the program entirely so that the camera is committed to the project at hand. - In other cases, the
attributeerror
comes from outdated versions of OpenCV, so try updating this version.
1. Check Path
As mentioned earlier, the major cause of the error is when you use an incorrect path. It is, therefore, a good idea to check if the path is present on the device or not with the help of the function os.path.exists()
method. The function os.getcws()
then prints the present directory and hence integral if you would wish to construct a path.
import os
print(os.path.exists('1.jpg'))
print(os.getcwd())
2. Use Try/Except
It is also possible to manage the error using the try/except statement. Here is how the solution works:
import cv2
img = cv2.imread('1.jpg')
try:
print(img.shape)
except AttributeError:
print('The ultimate value: ', img)
First, the try segment will run, and if an AttributeError
is encountered, then the except block executes.
3. Check if the Variable Is 'None' Using the 'If Else' Statement
To fix the error, you need to identify where the None
value comes from. Let's consider a common case where the error occurs; when working with a NumPy array. When working with a Numpy
array, you can get the error when working with an uninitialized array or one that has been assigned the value None
.
For example:
import numpy as np
arr = None
print(arr.shape)
The output for the above is:
AttributeError: 'NoneType' object has no attribute 'shape'
You can check a given statement and determine the type of variable it returns before accessing the shape attribute. Using the if-else
statement is useful in such cases, as it lets you know the shape
and returns None
when the shape
returns no value.
Here is an example:
import cv2
img = cv2.imread(r'C:\Users\ADMIN.DESKTOP-KB78BPH\Desktop\New folder
(5)\2.jpg')
if img is not None:
print(img.shape)
else:
print('variable is Nonetype object')
Output:
variable is Nonetype object
In the case above, we have first specified the absolute path. The if
block executes only when the variable stores a valid value that's not None
, and the else block executes when the variable value is None. We get the error message variable is Nonetype object
because the path does not exist. The steps work no matter the kind of operating system you are using, as you just have to input the path.
4. Initialize Array With Valid Values
Another option when you encounter an error while using Numpy
is that you ensure you use valid values. This can be achieved when we read data from a file or a different source or use Numpy
functions like zeros and ones.
Here we modify the code to initialize the array with zeros:
import numpy as np
arr = np.zeros((3, 3))
print(arr.shape)
Output:
(3, 3)
Conclusion
While AttributeError: NoneType
object has no attribute shape
is common in programming, there are several ways that you can opt for and solve it. The important thing is to ensure that before you try to access the shape attribute of an object, check if it is None
. If it is None
, then return None
else, return to shape
.
You can now solve the error and continue solving problems.