Python cv2.imread返回'NoneType'对象没有属性'shape'

2024-05-16 00:01:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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

回溯(最近的呼叫):

File "c:/Users/ramif/Desktop/Straßenverkehr Projekt/module.py", line 12, in read_image print(img.shape)

AttributeError: 'NoneType' object has no attribute '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()

Tags: pyimageimport文件夹readoscv2users
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()

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),您可以了解分隔符是什么

相关问题 更多 >