Python 列表理解 plt.imread 不起作用

Python list comprehension plt.imread does not work

我只是不明白python在这里做什么:

我想提供包含图像的目录的数学运算,并将它们作为列表中的 numpy 数组直接存储。 但是,当我执行以下代码时,一切正常,因为我首先提取文件名,然后执行 imread 以创建 numpy 数组:

def get_data(image_dir, annotations_dir):
  image_filenames = [ os.path.join(image_dir,i) for i in os.listdir(image_dir)]
  
  return image_filenames, image_filenames

IMAGE_DIR = os.path.join(os.getcwd(), "sample_data/images")
ANNOTATIONS_DIR = os.path.join(os.getcwd(), "sample_data/annotations")

print("IMAGE_DIR: {}\nANNOTATIONS_DIR: {}".format(IMAGE_DIR, ANNOTATIONS_DIR))

pet_images, pet_annotations = get_data(IMAGE_DIR, ANNOTATIONS_DIR)

print(len(pet_images))

my_img = plt.imread(pet_images[0])
plt.imshow(my_img)

结果:

IMAGE_DIR: /content/sample_data/images
ANNOTATIONS_DIR: /content/sample_data/annotations
7393

<matplotlib.image.AxesImage at 0x7feee24fdeb8>

(图像显示完美)

但是当我尝试直接在内部创建 numpy 数组时,它不起作用。下面是代码:


def get_data(image_dir, annotations_dir):
  image_filenames = [ plt.imread((os.path.join(image_dir,i)) for i in os.listdir(image_dir)]
  
  return image_filenames, image_filenames

IMAGE_DIR = os.path.join(os.getcwd(), "sample_data/images")
ANNOTATIONS_DIR = os.path.join(os.getcwd(), "sample_data/annotations")

print("IMAGE_DIR: {}\nANNOTATIONS_DIR: {}".format(IMAGE_DIR, ANNOTATIONS_DIR))

pet_images, pet_annotations = get_data(IMAGE_DIR, ANNOTATIONS_DIR)



plt.imshow(pet_images[0])

我得到:

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in open(fp, mode)
   2860         warnings.warn(message)
   2861     raise UnidentifiedImageError(
-> 2862         "cannot identify image file %r" % (filename if filename else fp)
   2863     )
   2864 

UnidentifiedImageError: cannot identify image file '/content/sample_data/images/Abyssinian_100.mat'

有人可以解释一下发生了什么以及为什么我不能直接在列表推导中使用 imread 创建 numpy 数组

此致

我发现了问题所在:代码崩溃的原因是数据集包含一个 filename.mat 文件,我的 imread 不支持该文件。