Reputation: 2789
I have a text file containing several images paths, suppose it is called DATA.TXT and the format is as follows:
Dataset_Eyes_Digital/RAW_Split/01401.png
Dataset_Eyes_Digital/RAW_Split/13349.png
Dataset_Eyes_Digital/RAW_Split/00134.png
...
However, these are not the real paths of the images. I have to add some strings to these paths when I read the text file line by line to get the absolute and real path of each image file, like as follows:
file1="DATA.TXT"
Lines = file1.readlines()
for line in Lines:
indices_name=line.split('/')
right_eye_path="/home/me/Desktop/"+indices_name[0]+"/"+indices_name[1]+"/Right/"+"right_"+indices_name[2]
left_eye_path="/home/me/Desktop/"+indices_name[0]+"/"+indices_name[1]+"/Left/"+"left_"+indices_name[2]
For example, the entry Dataset_Eyes_Digital/RAW_Split/01401.png in that text file would give me the following two image files:
right_eye_path=/home/me/Desktop/Dataset_Eyes_Digital/RAW_Split/Right/right_01401.png
left_eye_path=/home/me/Desktop/Dataset_Eyes_Digital/RAW_Split/Left/left_01401.png
Then, I just needed to read the files with opencv imread
left_eye_img = cv2.imread(left_eye_path, cv2.IMREAD_COLOR)
right_eye_img = cv2.imread(right_eye_path, cv2.IMREAD_COLOR)
My problem is: whenever I run and read the file paths with OpenCV, it returns me a NoneType. When I ask if the file exists, it says me it does not.
>> print(right_eye_img)
>> None
>> print(os.path.exists(right_eye_path))
>> False
However, if I open a python terminal and copy and paste the image path, it reads correctly. It also says to me that the image path exists, so probably the problem is the way I am treating the string variables in my code. How can I solve such an issue?
Upvotes: 0
Views: 491
Reputation: 126
You need to also do a .strip()
when you get lines from a file, since they contain a new line character at the end \n
Like so:
import os
file1 = "DATA.TXT"
f = open(file1, 'r')
lines = f.readlines()
for line in lines:
indices_name = line.strip().split('/')
right_eye_path = "/home/me/Desktop/" + indices_name[0] + "/" + indices_name[1] + "/Right/" + "right_" + indices_name[2]
left_eye_path = "/home/me/Desktop/" + indices_name[0] + "/" + indices_name[1] + "/Left/" + "left_" + indices_name[2]
print(right_eye_path)
print(left_eye_path)
print(os.path.exists(right_eye_path))
print(os.path.exists(left_eye_path))
Upvotes: 1