python - 从文本文件加载多个图像

标签 python opencv glob

我有40张图像,并且已经在一个文本文件中写下了它们的名称。现在,我想使用文本文件(在Python中)在程序中一一调用这些图像。

我已经使用glob查找所有图像名称(而不是文本文件)。
全局列表包含如下名称:

img=['image0.jpg','image1.jpg',....]

现在,如果我访问任何像img[0]img[1]的图像,它只是image0.jpg而不是'image0.jpg'
所以我在使用opencv函数加载时遇到了麻烦。
我想像加载它
cv.LoadImage('image0.jpg')

最佳答案

如果您的文件包含文件的标准名称。您可以执行以下操作

import cv
with open('textFileOfImages.txt','rb') as f:
    img = [line.strip() for line in f]

#load the images at you leisure
for image in img:
    loadedImage = cv.LoadImage(image)
    #manipulate image

如果文件包含当前工作目录中的相对路径,则:
import os
import cv
with open('textFileOfImages.txt','rb') as f:
    img = ['%s/%s'%(os.getcwd(),line.strip()) for line in f]

或者,如果您的文件包含目录的相对路径,则当前脚本正在运行
import os
import cv
with open('textFileOfImages.txt','rb') as f:
     img = ['%s/%s'%(os.path.dirname(os.path.abspath(__file__)),line.strip()) for line in f]

编辑

如果您需要从多个文件中加载图像名称,则可以轻松地将其合并。
假设您具有文件名列表,那么最简单的方法是在with语句外循环。
listOfFilenames = ['filename1.txt','filename2.txt','filename3.txt']
for filename in listOfFilenames: 
    with open(filename,'rb') as f:
    ...

关于python - 从文本文件加载多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19666356/

相关文章:

php - 如何使用 PHP 在目录中找到前 5 个文件?

php - Glob 模式不匹配任何内容

python - 在 Python 中使用字符串作为不完整的代码位

python - 在 Basemap 上绘制文本字符串代替 Python 中的点

python - Electron 问题运行manage.py运行服务器

c++ - 如何在托管类中使用非托管类?

image - 突出显示具有不同颜色图像的区域及其周围区域

python - 生成元素小于或等于给定列表的列表

matlab - 如何设置 Mat to Mat with a mask? (开放式简历)

windows - Windows文件模式中波浪号是什么意思