【发布时间】:2020-12-16 23:37:01
【问题描述】:
我只是不明白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 数组
最好的问候
【问题讨论】:
-
我认为您在
image_filenames = [ plt.imread((os.path.join(image_dir,i)) for i in os.listdir(image_dir)]这一行上有一个额外的括号,但我认为您会遇到语法错误。 -
我发现了问题所在:代码崩溃的原因是数据集包含我的 imread 不支持的 filename.mat 文件。
标签: python numpy list-comprehension imshow imread