Python 指定文件位置目录

Python specifying file location directory

我在 Windows 7 机器上使用 Python 64 位 IDLE 来尝试为 opencv 机器学习编写脚本。我想弄清楚为什么我下面的代码找不到我的图片文件在我的 Windows PC 上的目录。

有更好的方法吗? IDLE 中的 shell 输出没有任何反应,我希望打印功能能够正常工作。

我的 C:drive 上一个名为 faces 的文件夹中有 .py 文件,如下所示。 C:\Users\ben\Documents\Python\opencv\Faces\images\ben

图片文件位于Faces\images\ben

import cv2
import os
import numpy as np
from PIL import Image
import pickle

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images")

for root, dirs, files in os.walk(image_dir):
    for file in files:
        if file.endswith("png") or file.endswith("JPEG"):
            path = os.path.join(root, file)
            label = os.path.basename(root).replace(" ", "-").lower()
            print(path)

因为,您的代码文件放在 Faces 文件夹中 图片路径如下

loc = os.path.join(os.path.join(os.path.dirname(__file__),"images"),"ben")

如果您的 python 个文件在

C:\Users\ben\Documents\Python\opencv\Faces  

图像在

C:\Users\ben\Documents\Python\opencv\Faces\images\ben

然后:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images", "ben")

如果仍然出现问题,请尝试手动构建 image_dir:

image_dir = "%s\%s\%s"%(BASE_DIR, "images", "ben")