【问题标题】:openCV python is not reading my images, path does not existopenCV python没有读取我的图像,路径不存在
【发布时间】:2021-03-12 10:51:26
【问题描述】:

我有一个包含多个图片路径的文本文件,假设它叫DATA.TXT,格式如下:

Dataset_Eyes_Digital/RAW_Split/01401.png
Dataset_Eyes_Digital/RAW_Split/13349.png
Dataset_Eyes_Digital/RAW_Split/00134.png
...

但是,这些并不是图像的真实路径。当我逐行读取文本文件时,我必须在这些路径中添加一些字符串,以获取每个图像文件的绝对路径和真实路径,如下所示:

 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]

例如,该文本文件中的条目 Dataset_Eyes_Digital/RAW_Split/01401.png 将为我提供以下两个图像文件:

 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

然后,我只需要使用 opencv imread 读取文件

 left_eye_img = cv2.imread(left_eye_path, cv2.IMREAD_COLOR)
 right_eye_img = cv2.imread(right_eye_path, cv2.IMREAD_COLOR)

我的问题是:每当我使用 OpenCV 运行和读取文件路径时,它都会返回一个 NoneType。当我询问文件是否存在时,它说我不存在。

>> print(right_eye_img)
>> None
>> print(os.path.exists(right_eye_path)) 
>> False

但是,如果我打开 python 终端并复制并粘贴图像路径,它会正确读取。它还告诉我图像路径存在,所以问题可能是我在代码中处理字符串变量的方式。我该如何解决这样的问题?

【问题讨论】:

  • 你也可以:print(right_eye_path) 吗?
  • @voyager42 当我打印时,会出现正确的名称。如果我复制并粘贴到 Python 终端,它就可以工作。现在问题已经解决了。谢谢

标签: python string opencv


【解决方案1】:

当您从文件中获取行时,您还需要执行.strip(),因为它们在末尾包含一个换行符\n

像这样:

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2011-03-15
    • 2018-03-14
    • 1970-01-01
    • 2022-01-19
    • 2020-08-13
    相关资源
    最近更新 更多