如果您的文件包含文件的完全限定名称。您可以执行以下操作
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:
...