python - 错误 'NoneType' 对象不可下标是什么意思

标签 python artificial-intelligence

我正在从事人脸识别项目,在其中训练模型。预测 我加载图像并想要计算 2 个图像之间的距离。在预测时我遇到以下错误:

             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

代码如下

      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)

加载图片代码如下:

       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]

由于我是 python 新手,我无法理解这个错误的含义

最佳答案

>>> None == type(None)
False

因此,如果 cropped_img 为 None,则比较 if(cropped_img == type(None)): 将为 False。因此, cropped_img = np.zeros(shape = (224, 224)) 永远不会被执行,因此 cropped_img 将保持 None 并将被传递到 load_image,正如错误消息所示,它不适用于 None

你应该这样检查:

if cropped_img is None:
    cropped_img = np.zeros(shape = (224, 224))

关于python - 错误 'NoneType' 对象不可下标是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59200169/

相关文章:

python - 已通过 Selenium 使用 GeckoDriver Firefox 丢弃浏览上下文

python - vscode python 格式化 autopep8 禁用 E266

python - 如何加入两个子进程的标准输出并通过管道连接到python中新子进程的标准输入

python - 动态变量创建

artificial-intelligence - 爬山算法简单例子

python - 字符串格式化和解析

artificial-intelligence - 大脑建模

algorithm - Solarmax 等策略游戏的人工智能

java - 无法确定我的 IDA* 实现是否存在错误或效率低下

machine-learning - 机器学习(无监督方法)