我正在用Youtube教程在Python中构建AI图像分类器,但运行未完成的程序时无法打开图像

-2 投票
1 回答
36 浏览
提问于 2025-04-12 16:31

我正在尝试根据一个YouTube教程制作一个AI图像分类器,这是我为学校项目做的。这里是链接:https://www.youtube.com/watch?v=oEKg_jiV1Ng&t=727s

目前我还没完成,但当我运行我的main.py时,出现了以下错误:

Traceback (most recent call last):
  File "c:\xxx\xx\xx\xx\newai\main.py", line 19, in <module>
    for img_path in os.listdir(os.path.join(dir_, category)):
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:/xx/xx/xx/xx/newai\\Data\\Blue-Squares\\BlueSquare (1).jpg'

我还收到了这个错误,不过我觉得对项目影响不大。(也许有影响,我只是觉得既然视频里能运行,那它应该也能在我这儿运行,因为这个视频是最近的。):

:\XX\XX\XX\XX\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\torchvision\models\_utils.py:208: UserWarning: The parameter 'pretrained' is deprecated since 0.13 and may be removed in the future, please use 'weights' instead.
  warnings.warn(
C:\XX\XX\XX\XX\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\torchvision\models\_utils.py:223: UserWarning: Arguments other than a weight enum or `None` for 'weights' are deprecated since 0.13 and may be removed in the future. The current behavior is equivalent to passing `weights=ResNet18_Weights.IMAGENET1K_V1`. You can also use `weights=ResNet18_Weights.DEFAULT` to get the most up-to-date weights.
  warnings.warn(msg)

在视频中,当他在这个阶段运行时,会打印出一些键,并且运行得很好。

这是我的完整代码:

from img2vec_pytorch import Img2Vec
import os
from PIL import Image

# prepare data

img2vec = Img2Vec()

data_dir = 'C:/XX/XX/XX/XX/newai'
train_dir = os.path.join(data_dir, r'Data', r'Blue-Squares')
val_dir = os.path.join(data_dir, r'Data', r'Red-Triangles')

data = {}

for j, dir_ in enumerate([train_dir, val_dir]):
    features = []
    labels = []
    for category in os.listdir(dir_):
        for img_path in os.listdir(os.path.join(dir_, category)):
            img_path_ = os.path.join(dir_, category, img_path)
            img = Image.open(img_path_)

            img_features = img2vec.get_vec(img)

            features.append(img_features)
            labels.append(category)

    data[['training_data', 'validation_data'][j]] = features
    data[['training_labels', 'validation_labels'][j]] = labels


print(data.keys())

# train model

# test performance

# save the model

我尝试过:复制并粘贴YouTuber的代码,完全按照他的来,换路径,换文件夹,换图像名称,改变设置方式,搜索错误等等。我知道图像不是一个目录,所以我明白这一点,但我就是不知道该改什么。任何反馈都将非常感谢。

1 个回答

-1

在这个视频里,讲解的人使用的是Linux系统。而从你的代码来看,你使用的是Windows系统。Linux和Windows的文件路径写法是不同的,所以你需要调整一下文件夹的路径,让它适合Windows。在Windows中,路径是用反斜杠 '\' 来表示的,而在Linux中,路径是用正斜杠 '/' 来表示的。

撰写回答