首页 > 解决方案 > 如何从文本文件中的 jpeg 图像文件列表中打开图像 - 变量形成

问题描述

我有一个文本文件,其中包含要导入脚本的 jpeg 图像的路径。我正在使用 Udemy 课程提供的示例代码:“使用 Python 进行深度学习 - 从新手到专业!” 检测图像中的微笑。我遇到问题的功能是将图像转换为矩阵/二维数组:

def img2array(f, detection=False, ii_size=(64, 64)):
"""
Convert images into matrixes/two-dimensional arrays.

detection - if True we will resize an image to fit the
            shape of a data that our first convolutional
            layer is accepting which is 32x32 array,
            used only on detection.

ii_size - this is the size that our input images have.
"""
rf=None
if detection:
    rf=f.rsplit('.')
    rf=rf[0]+'-resampled.'+rf[1]
    im = Image.open(f)
    # Create a smaller scalled down thumbnail
    # of our image.
    im.thumbnail(ii_size)
    # Our thumbnail might not be of a perfect
    # dimensions, so we need to create a new
    # image and paste the thumbnail in.
    newi = Image.new('L', ii_size)
    newi.paste(im, (0,0))
    newi.save(rf, "JPEG")
    f=rf
# Turn images into an array.
data=imread(f, as_gray=True)
# Downsample it from 64x64 to 32x32
# (that's what we need to feed into our first convolutional layer).
data=block_reduce(data, block_size=(2, 2), func=np.mean)
if rf:
    remove(rf)
return data

该函数在另一个脚本中调用:

    img_data=prep_array(img2array(filename, detection=True), detection=True)

我不确定如何命名“文件名”以使此代码正确运行。当我给它文本文件路径时,我收到一条错误消息:

UnidentifiedImageError:无法识别图像文件'filepath\imagelist.txt

我是 Python 的新手,我需要帮助导入正确的“文件名”变量以使此功能正常工作。

标签: pythonimage-processingimportpathpython-3.6

解决方案


从错误消息的外观来看,您将文本文件的文件路径(包含图像的路径)传递为filename

解析文本文件以获取图像的文件路径并将其传递给您的函数。

with open("path/to/imagelist.txt", "r") as fp:
    filepaths = fp.read().splitlines()
    for filename in filepaths:
        img_data=prep_array(img2array(filename, detection=True), detection=True)


推荐阅读