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

Viewed 3888

i'm newbie so i don't understand why am i getting error "AttributeError: 'NoneType' object has no attribute 'size'"?

img = cv2.imread('cat.jpg')
print("Image Properties")
print("- Number of Pixels: " + str(img.size))
print("- Shape/Dimensions: " + str(img.shape))```
4 Answers

This is probably caused by lack of cat.jpg file, please import os and add

print(os.path.exists('cat.jpg'))

immediately before

img = cv2.imread('cat.jpg')

If it outputs False this mean cat.jpg is not there. You might use print(os.getcwd()) to check where cat.jpg should be placed xor provide full path to file to solve this issue.

You are getting this error on line 3 because you are taking the size of img, and img is (according to the interpreter), None.

So why is it None? You want to look at its definition.

img = cv2.imread('cat.jpg')

So what happens is that imread returns None. When does that happen? When the file doesn’t exist.

Therefore, the file cat.jpg is not in the working directory of your python program.

Therefore you will want to check if your program was launched in the right directory (or use os.chdir to change the directory).

The img has no attribute named size

Looks like the cv2.imread('cat.jpg') is returning unexpected value. Try printing img and then you can debug further. Maybe it can't find the cat.png file in the specified location.

The object img is invalid so it can't have any properties (like size). So when you ask for the size, there's nothing associated with the size attribute.

The problem is either:

  1. The file is corrupted in some shape or form
  2. The path is incorrect (try to use absolute paths)
  3. The file doesn't exist

Relative path: \photos_folder\cat.jpg
Absolute path: C:\users\donkey\Documents\project_1\photos_folder\cat.jpg

Related