【问题标题】:Python cv2.imread returns 'NoneType' object has no attribute 'shape'Python cv2.imread 返回“NoneType”对象没有属性“形状”
【发布时间】:2020-09-19 03:04:04
【问题描述】:

我正在尝试使用 cv2.imread 从名为“Bilder”的文件夹中读取我的图片,但我总是没有返回任何内容。当我将图片放入“Straßenverkehr Projekt”文件夹(我的代码 [module.py] 也保存在该文件夹中)时,它就可以工作了。

图片文件夹路径:C:\Users\ramif\Desktop\Straßenverkehr Projekt\Bilder

代码文件夹路径:C:/Users/ramif/Desktop/Straßenverkehr Projekt/module.py

回溯(最近一次调用):

文件“c:/Users/ramif/Desktop/Straßenverkehr Projekt/module.py”,行 12、在read_image中打印(img.shape)

AttributeError: 'NoneType' 对象没有属性 'shape'

import cv2
import matplotlib.pyplot as plt
import numpy as np
import os

def read_image():
    'reading the images'
    folder = os.path.join(os.path.dirname(__file__),"Bilder")
    for i in os.listdir(folder):
        img = cv2.imread(i)
        print(img.shape)

read_image()

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    cv2.imread 的一个令人讨厌的特性是,如果出现错误,它不会引发异常。您必须检查返回值。 “NoneType”始终是它找不到文件的线索。有很多方法可以解决这个问题。从您的代码开始,我能想到的最简单的方法是使用os.chdir 将工作目录更改为图片所在的位置:

    import cv2
    import matplotlib.pyplot as plt
    import numpy as np
    import os
    
    def read_image():
        'reading the images'
        folder = os.path.join(os.path.dirname(__file__),"Bilder")
        os.chdir(folder)
        for i in os.listdir(folder):
            img = cv2.imread(i)
            print(img.shape)
    
    read_image()
    

    另一种解决方案是在 for 循环中使用 os.path.join,即

    for i in os.listdir(folder):
        fullpath = os.path.join(folder, i)
        img = cv2.imread(fullpath)
        print(img.shape)
    

    @gautam-bose 答案应该适用于 Linux 系统,但我忘记了 Python 希望路径分隔符在 Windows 中的样子。如果您print(folder),您可以了解分隔符是什么。

    【讨论】:

      【解决方案2】:

      问题在于 os.listdir 只提供了 Bilder 文件夹中的文件名。要使此示例正常工作,您需要将目录附加到文件名,以便获得图像的完整路径。

      import cv2
      import matplotlib.pyplot as plt
      import numpy as np
      import os
      
      def read_image():
          'reading the images'
          folder = os.path.join(os.path.dirname(__file__),"Bilder")
          for i in os.listdir(folder):
              img = cv2.imread(folder + '/' + i)
              print(img.shape)
      
      
      read_image()
      

      【讨论】:

      • 不幸的是它仍然给我同样的错误
      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 2013-07-30
      • 2016-05-09
      • 2015-05-07
      • 2017-02-11
      • 2021-12-26
      相关资源
      最近更新 更多