1

I am working on face recognition project , in which I train the model. prediction I load images and want to calculate distanse betwwen 2 images. while predection i am getting below error:

             TypeError                                 Traceback (most recent call last)
       <ipython-input-21-0b1f36824e17> in <module>()
  8   if(cropped_img == type(None)):
  9     cropped_img = np.zeros(shape = (224, 224))
  ---> 10   img = (load_image(cropped_img) / 255.).astype(np.float32)
 11   img = cv2.resize(img, dsize = (224,224))
 12   embedding_vector = vgg_face_descriptor.predict(np.expand_dims(img, axis=0))[0]

 <ipython-input-9-6d96fb74d85b> in load_image(path)
  4     # OpenCV loads images with color channels
  5     # in BGR order. So we need to reverse them
  ----> 6     return img[...,::-1]

 TypeError: 'NoneType' object is not subscriptable

code is below

      NoneType = type(None)


embedding =[]
for i, m in enumerate(metadata):
   cropped_img = m.image_path()
   print(i)
  if(cropped_img == type(None)):
     cropped_img = np.zeros(shape = (224, 224))
  img = (load_image(cropped_img) / 255.).astype(np.float32)
  img = cv2.resize(img, dsize = (224,224))
  embedding_vector = vgg_face_descriptor.predict(np.expand_dims(img, axis=0))[0]

  embedding.append(embedding_vector)

Load image code is as below:

       def load_image(path):
         img = cv2.imread(path, 1)
         # OpenCV loads images with color channels
         # in BGR order. So we need to reverse them
         return img[...,::-1]

As I am new to python I can not understand what this error means

Rajanikant Shukla
  • 841
  • 2
  • 8
  • 11

2 Answers2

1
>>> None == type(None)
False

So, if cropped_img is None, your comparison if(cropped_img == type(None)): will be False. And thus, cropped_img = np.zeros(shape = (224, 224)) will never be executed, so cropped_img will remain None and will be passed on to load_image, which, as the error message shows, doesn't work with None.

You should check like this:

if cropped_img is None:
    cropped_img = np.zeros(shape = (224, 224))
ForceBru
  • 43,482
  • 10
  • 63
  • 98
-1

below code will resolve the problem as imread gives None

     def load_image(path):
       img = cv2.imread(path, 1)
        if type(img) == type(None):
           img = np.zeros(shape = (224, 224))
     # OpenCV loads images with color channels
     # in BGR order. So we need to reverse them
       return img[...,::-1]
Rajanikant Shukla
  • 841
  • 2
  • 8
  • 11
  • `if type(img) == type(None):` -> `if img is None:` -> maybe even `if not img:`. – AMC Dec 08 '19 at 05:10