python中imread的相对路径

时间:2018-02-01 08:18:40

标签: python opencv

我无法在imread中设置DSC_1902.JPG图像(在“Res”目录中)的相对路径。以下是我的项目结构:

  

BasicAI Server / Res / DSC_1902.JPG

     

BasicAI Server / Computer_Vision / FD.py

以下代码位于FD.py

import cv2
def detect():

    img = cv2.imread('\BasicAI Server\Res\DSC_1902.JPG')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

detect()

1 个答案:

答案 0 :(得分:1)

最好通过使用os.path.join函数构建与平台无关的路径字符串来避免路径中的斜杠。

可以使用path.join模块中的函数getcwdos将相对路径转换为绝对路径,如下所示:

import cv2
import os
def detect():
    absolute_path = os.path.join(os.getcwd(), 'BasicAI Server', 'Res', 'DSC_1902.JPG');
    img = cv2.imread(absolute_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

detect()

如果代码是从 BasicAI Server 目录的父目录执行的话,这将有效。