python - 如何从文本文件中的 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 的新手,我需要帮助导入正确的“文件名”变量以使此功能正常工作。
解决方案
从错误消息的外观来看,您将文本文件的文件路径(包含图像的路径)传递为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)
推荐阅读
- r - 如何从不同间隔的列表中提取值(由列表定义)
- r - 使用 ID 聚合某些列中的行,并在大型 R 数据框中保持其他列不变
- wordpress - 通过functions.php替换部分标题
- database - 如何在 Cassandra 中存储使用活动数据
- c# - 我如何使用表格视图和选择器作为用户输入?
- git - 将本地代码库恢复到特定的 Heroku 版本
- python - 如何使用 pandas 库将数据写入 excel 文件?
- javascript - 如何根据高度在javascript中对矩形进行排序
- database - 是否有任何方法可以根据从 MS 访问中的查找字段中选择的值来存储特定的数值
- centos - 如何修复openproject配置上的“无事可做”错误?