Reputation: 442
I have got 40 images,and I have written their names in a text file. Now I want to call those images one by one in my program,using that text file (in Python).
I have used glob to find all image names,(instead of text file). glob list contains of names like that:
img=['image0.jpg','image1.jpg',....]
Now If I access any image like img[0]
,img[1]
it is just image0.jpg not 'image0.jpg'
,
so I have got trouble loading using opencv
function to load it.
I want to load it like
cv.LoadImage('image0.jpg')
Upvotes: 0
Views: 2780
Reputation: 1095
If your file contains the fully-qualified names of the files. You can do the following
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
If your file contains the relative path from the current working directory then:
import os
import cv
with open('textFileOfImages.txt','rb') as f:
img = ['%s/%s'%(os.getcwd(),line.strip()) for line in f]
Or if your file contains the relative path from directory the current script is running
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]
If you need to load image names from multiple files you can easily incorporate this.
Assuming you have the list of file names, then the easiest way is to loop outside the with
statement.
listOfFilenames = ['filename1.txt','filename2.txt','filename3.txt']
for filename in listOfFilenames:
with open(filename,'rb') as f:
...
Upvotes: 1
Reputation: 947
Try using
for _file in img:
cv.LoadImage("{0}".format(_file))
if your file is in other directory,
import os
for _file in img:
cv.LoadImage("{0}".format(os.path.join(directory, _file)))
Upvotes: 0