如何解决Python代码中的‘AttributeError: 'NoneType' object has no attribute 'shape'’错误?
Fixing the 'AttributeError: 'NoneType' object has no attribute 'shape'' in Your Python Code
Hey there, let's break down why you're hitting this error and fix it step by step!
What's Causing the Error?
The error pops up because cv2.imread(data[i]) is returning None—meaning OpenCV couldn't successfully load the image file you're trying to read. When you try to access the .shape attribute of a None object, Python throws that AttributeError.
Common reasons this happens:
- The image path is incorrect, or the file doesn't exist (maybe
globpicked up a non-image file?) - The image file itself is corrupted and can't be loaded
- The image format isn't supported by OpenCV (rare for common formats like JPG/PNG, but possible for niche ones)
How to Fix It
We'll modify your code to add checks for successful image loading, plus make path handling more cross-platform friendly. Here's the updated code:
import os import glob import cv2 # Assume your classes, TRAIN_DIR, and class2label variables are already defined categories = [] image_name = [] image_id = [] image_format = [] labels = [] img_path = [] img_height = [] img_width = [] for cat in classes: path = os.path.join(TRAIN_DIR, cat, "*") data = glob.glob(path) for img_file in data: # First, attempt to load the image and check if it succeeded img = cv2.imread(img_file) if img is None: print(f"Warning: Failed to load image at {img_file}. Skipping this file.") continue # Now safely get the image dimensions h, w, c = img.shape # Use os.path utilities for cross-platform path handling (works on Windows/macOS/Linux) cls = os.path.basename(os.path.dirname(img_file)) img_name = os.path.basename(img_file) img_id_part, img_format_part = os.path.splitext(img_name) # Remove the leading dot from the format (e.g., ".jpg" becomes "jpg") img_format_part = img_format_part.lstrip('.') # Append data to your lists img_height.append(h) img_width.append(w) categories.append(cls) image_name.append(img_name) image_id.append(img_id_part) image_format.append(img_format_part) labels.append(class2label[cls]) img_path.append(img_file)
Key Improvements in the Updated Code
- Image loading check: We added
if img is Noneto catch failed loads, print a warning, and skip the problematic file instead of crashing. - Cross-platform path handling: Replaced manual
/splitting withos.pathmethods, which work regardless of your operating system's path separator. - Cleaner format extraction: Used
os.path.splitextto safely get the file extension, then stripped the leading dot for consistency.
Extra Troubleshooting Tips
- Double-check that
TRAIN_DIRpoints to the correct root directory of your training images. - Open the files mentioned in the warning messages to see if they're corrupted or not actually image files.
- If
globis picking up non-image files, narrow your path pattern to specific formats (e.g.,"*.jpg"or"*.png") instead of"*".
内容的提问来源于stack exchange,提问作者farhad_bme




