我有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/