DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • SmartXML: An Alternative to XPath for Complex XML Files
  • Efficient String Formatting With Python f-Strings
  • Java String: A Complete Guide With Examples
  • Generics in Java and Their Implementation

Trending

  • Designing a Java Connector for Software Integrations
  • Mastering Advanced Aggregations in Spark SQL
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  1. DZone
  2. Data Engineering
  3. Data
  4. Fix AttributeError: 'NoneType' Object Has No Attribute 'Shape'

Fix AttributeError: 'NoneType' Object Has No Attribute 'Shape'

Learn how to master Pandas and NumPy development errors is easy with our effective solutions.

By 
Ankur Ranpariya user avatar
Ankur Ranpariya
·
Jul. 07, 23 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
3.0K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Python
 
import numpy as np
arr = np.array([[5, 1], [16, 33]])
print(arr.shape)


Output:

Python
 
(2, 2)


The shape attribute is also important in pandas or OpenCV.

Here is how the shape attribute is used in OpenCV:

Python
 
import cv2
img = cv2.imread(r'C:\Users\ADMIN.DESKTOP-KB78BPH\Desktop\New folder
(2)\2.jpg')
print(img.shape)


The output is:

Python
 
(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.

Python
 
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:

Python
 
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:

Python
 
import numpy as np
arr = None
print(arr.shape)


The output for the above is:

Python
 
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:

Python
 
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:

Python
 
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:

Python
 
import numpy as np
arr = np.zeros((3, 3))
print(arr.shape)


Output:

Python
 
(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.

Data structure Error message NumPy OpenCV Attribute (computing) Object (computer science)

Published at DZone with permission of Ankur Ranpariya. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • SmartXML: An Alternative to XPath for Complex XML Files
  • Efficient String Formatting With Python f-Strings
  • Java String: A Complete Guide With Examples
  • Generics in Java and Their Implementation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!