简体   繁体   English

如何从文本文件中的 jpeg 图像文件列表中打开图像 - 变量格式

[英]How to open an image from a list of jpeg image files in text file - variable formation

I have a text file that contains the paths to jpeg images I want to import into my script.我有一个文本文件,其中包含要导入脚本的 jpeg 图像的路径。 I am using an example code provided by a Udemy course: "Deep Learning with Python - Novice to Pro!"我正在使用 Udemy 课程提供的示例代码:“使用 Python 进行深度学习 - 从新手到专业!” that detects smiles in images.检测图像中的微笑。 The function I am having trouble with is converting images into matrixes/two-dimensional arrays:我遇到问题的功能是将图像转换为矩阵/二维数组:

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

The function is called in another script:该函数在另一个脚本中调用:

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

I am not sure what to name 'filename' in order for this code to run correctly.我不确定要命名“文件名”以便此代码正确运行。 When I give it the text file path I get an error that says:当我给它文本文件路径时,我收到一条错误消息:

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

I am brand new to Python, and I need help importing the correct 'filename' variable to make this function work.我是 Python 的新手,我需要帮助导入正确的“文件名”变量以使此函数工作。

From the looks of the error message, you're passing in the file path of the textfile (containing paths to images) as filename从错误消息的外观来看,您将文本文件的文件路径(包含图像路径)作为filename传递

Parse the text file for file paths to images and pass it into your function.解析文本文件以获取图像的文件路径并将其传递到您的函数中。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM