[Solved] AttributeError: ‘NoneType’ object has no attribute ‘shape’

import numpy as np 
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('AB.jpg')
mask = np.zeros(img.shape[:2] , np.uint8) 

bgdModel = np.zeros((1,65), np.float64)
fgdModel = np.zeros((1,65), np.float64)

rect = (300 , 120 , 470 , 350)

#this modifies mask
cv2.grabCut(img,mask,rect,bgdModel, fgdModel , 5 , cv2.GC_INIT_WITH_RECT)

#If mask==2 or mask==1 , mask2 get 0, otherwise it gets 1 as 'uint8' type
mask2 = np.where((mask==2) | (mask==0),0,1).astype('uint8')

#adding additional dimension for rgb to the mask, by default it gets 1
#multiply with input image to get the segmented image
img_cut = img*mask2[: , : , np.newaxis]

plt.subplot(211),plt.imshow(img)
plt.title('Input Image') , plt.xticks([]),plt.yticks([])
plt.subplot(212),plt.imshow(img_cut)
plt.title('Grab cut'), plt.xticks([]),plt.yticks([])
plt.show()

on compiling I get this error :

python img.py AB.jpg
Traceback (most recent call last):
File "img.py", line 6, in <module>
mask = np.zeros(img.shape[:2] , np.uint8) 
AttributeError: 'NoneType' object has no attribute 'shape'
Enquirer: AK47

||

Solution #1:

First of all

python img.py AB.jpg

will not work as you expect (load AB.jpg from the current directory). The file to load is hardcoded in line 6 of the provided example: to work as intended, it should be something like this:

import sys
img = cv2.imread(sys.argv[1])

The error is returned because AB.jpg does not exist in the directory img.py is being run from (the current working directory), and there is no verification for a missing file before trying to read it.

Respondent: Emanuele Cipolla

Solution #2:

Answering, because the community brought it back. Adding my two objects (cents).

The only reason you see that error is because you are trying to get information or perform operations on an object that doesn’t exist in the first place. To check, try printing the object. Like, adding –

print img      # such as this case
print contours # if you are working with contours and cant draw one
print frame    # if you are working with videos and it doesn't show

gives you a None. That means you haven’t read it properly. Either the image name you gave does not exist or the path to it is wrong. If you find such an error here’s the quick things to do-

  1. Check the path or bring your image to the working directory
  2. Check the name you gave is right (including the extension- .jpg, .png etc)
  3. Put the entire code in a if statement with the object and the code to proceed if true
  4. Will add more if suggested in the comments.
Respondent: I.Newton

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.