1

该文件显然存在,但 imread() 无法识别图像。有什么我想念的吗?我对 python 及其各自的库仍然很陌生。

代码(Python 3.7.9)

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


from randomlyShiftChannels import *
from alignChannels import *
from utils import *

#Path to your data directory
data_dir = os.path.join('..', 'data', 'demosaic')

#List of images
image_names = ['balloon.jpeg','cat.jpg', 'ip.jpg',
            'puppy.jpg', 'squirrel.jpg', 'pencils.jpg',
            'house.png', 'light.png', 'sails.png', 'tree.jpeg'];

print('Evaluating alignment...')
for imgname in image_names:
    # Read image
    imgpath = os.path.join(data_dir, imgname)
    print("File exists:", os.path.exists(imgpath))
    img = imread(imgpath)

输出

File exists: True
Traceback (most recent call last):

  File "D:\Spring2021\CS370\week 6\p2-release\code\evalAlignment.py", line 48, in <module>
    img = imread(imgpath)

  File "D:\Spring2021\CS370\week 6\p2-release\code\utils.py", line 14, in imread
    img = plt.imread(path).astype(float)

  File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\matplotlib\pyplot.py", line 2246, in imread
    return matplotlib.image.imread(fname, format)

  File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\matplotlib\image.py", line 1496, in imread
    with img_open(fname) as image:

  File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\PIL\Image.py", line 2944, in open
    "cannot identify image file %r" % (filename if filename else fp)

UnidentifiedImageError: cannot identify image file '..\\data\\demosaic\\balloon.jpeg'
4

2 回答 2

0

尝试将您的路径转换为绝对路径,我们称之为良好实践是有原因的

示例代码:

import os
os.path.abspath("mydir/myfile.txt") #'C:/example/cwd/mydir/myfile.txt'
于 2021-03-02T03:14:54.643 回答
0

我使用 Spyder(Spyder 5.0.0 和 5.0.1)遇到了同样的问题。从命令行运行脚本时没有出现错误。

找到 Spyder 的解决方法:使用 pil_to_array() 而不是 imread()

from PIL import Image

img = pil_to_array(Image.open(imgpath))
于 2021-04-20T06:13:18.167 回答