【问题标题】:FileNotFoundError in PIL image with relative path and absoulute path具有相对路径和绝对路径的 PIL 图像中的 FileNotFoundError
【发布时间】:2021-05-10 15:45:42
【问题描述】:
import PIL.Image as pilimg
import numpy as np

# Read image
im = pilimg.open("../dataset/start.jpg")

# Display image
im.show()

# Fetch image pixel data to numpy array
pix = np.array(im)

(我不是数据集的作者,所以无法上传整个项目文件。)

我正在尝试使用 Pillow 读取图像并将其转换为 NumPy 数组。但是,我尝试了几种方法,例如使用绝对路径和PIL image.open() working for some images but not others 中的方法,除了使用 OpenCV 的方法。但是,它总是导致 FileNotFound。

start.jpg 的绝对路径是F:\GIST 강의 자료\2021 1학기\EC3202 신호 및 시스템\Programming Assignment\dataset\start.jpg。我相信从src/program.pystart.jpg 的相对路径是../dataset/start.jpg

我正在使用 conda 4.10.1 和 python 3.8.8 和 windows 10。

【问题讨论】:

  • 你可以尝试通过print(f"Current working dir: {os.getcwd()})获取你的实际工作目录
  • @user_na 我应该从 bash shell 还是 python 提示符运行它?
  • 在使用图像之前在代码中打印并像往常一样运行它
  • @user_na 我在注释中添加代码,它显示当前工作目录:F:\GIST 강의 자료\2021 1학기\EC3202 신호 및 시스템\Programming Assignment
  • @user_na 文件导入的依据是工作目录,而不是导入图片的源代码文件的位置?

标签: python python-imaging-library file-not-found


【解决方案1】:

路径是相对于当前工作目录的。 如果您不确定 cwd 是什么,您可以通过以下方式找到它:

print(f"Current working dir: {os.getcwd()})

然后您可以使用os.path.join 从那里连接您的相对路径

os.path.join(os.getcwd(),'dataset/start.jpg')

【讨论】:

    【解决方案2】:

    不要依赖 os.getcwd 获取相对路径。原因如下。

    改为使用pathlib.Path。即考虑这些结构。

    x:/
     ├ A
     ┃ ├ 1.png
     ┃ ├ 2.png
     ┃ ├ 3.png
     ┃ ├ 4.png
     ┃ └ 5.png
     ┃
     └ B
       └ script.py
    

    如果你想可靠地script.py访问1.png,你最好使用__file__来确定脚本的路径——作为当前工作目录可能与实际脚本位置不同,如下面的示例输出所示。

    import pathlib
    import os
    
    print("Current cwd: ", os.getcwd())
    
    # Get current script's folder
    script_location = pathlib.Path(__file__).parent
    
    # get data folder
    data_location = script_location.parent.joinpath("A")
    
    # single file example
    png_file = data_location.joinpath("1.png")
    
    # alternatively can iterate thru directory
    for file_ in data_location.iterdir():
    
        # print full path in linux style
        print(f"{file_.absolute().as_posix()}")
    
    
    (Accessing file in different path in absolute path)
    
    jupiterbjy@NYARUDESK/D: py X:\B\script.py
    Current cwd:  D:\
    X:/A/1.png
    X:/A/2.png
    X:/A/3.png
    X:/A/4.png
    X:/A/5.png
    
    
    (Change directory)
    
    jupiterbjy@NYARUDESK/D: 
    ❯ cd x:
    
    
    (Now use indirect path)
    
    jupiterbjy@NYARUDESK/X: py .\B\script.py
    Current cwd:  X:\
    X:/A/1.png
    X:/A/2.png
    X:/A/3.png
    X:/A/4.png
    X:/A/5.png
    

    查看 cwd - 当前工作目录 - 每次运行时 os.getcwd 的不同之处。

    但是,无论您在何处通过间接或直接、外部或内部文件夹B 访问该脚本,您都可以使用__file__.parent.joinpath 方法相对可靠地访问文件pathlib.Path 个对象。

    查看pathlibhere的文件,我看你是韩国人,这是链接到韩国文件的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-15
      • 2012-01-10
      • 2014-02-06
      • 2013-07-14
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      相关资源
      最近更新 更多