【问题标题】:img = cv.imread(f'{x}.png')[:,:,0] TypeError: 'NoneType' object is not subscriptable (Machine learning problem)img = cv.imread(f'{x}.png')[:,:,0] TypeError: 'NoneType' 对象不可下标(机器学习问题)
【发布时间】:2025-12-09 10:45:01
【问题描述】:

我正在尝试学习机器学习,因此我正在学习如何训练网络识别数字的教程。我正处于训练网络的阶段,我正在尝试一些我自己的图像。但是,不知何故,识别图像存在问题。我不确定我做错了什么。我已将图像上传到同一目录文件夹中。您可以在下面找到代码和错误。

错误

img = cv.imread(f'{x}.png')[:,:,0]

TypeError: 'NoneType' object is not subscriptable

我也收到了这个错误,虽然它似乎没有影响任何东西。我应该担心吗?

2021-08-04 17:53:03.097193: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2021-08-04 17:53:03.099366: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):

代码

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(units=128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(units=128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(units = 10, activation=tf.nn.softmax))

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(x_train, y_train, epochs=3)

accuracy, loss = model.evaluate(x_test, y_test)
print(accuracy)
print(loss)

model.save('digits.model')

for x in range(1,6):
    img = cv.imread(f'{x}.png')[:,:,0]
    img= np.array([img])
    plt.imshow(img[0], cmap=plt.cm.binary)
    plt.show()

【问题讨论】:

  • 这看起来文件名在某种程度上是无效的,因为您只是假设 imread 有效,而不是确保它找到了文件。可能路径错误,或者文件系统区分大小写并且您的文件名错误。
  • @Donnie 谢谢。我确实没有通过检查文件名。如此明显的细节,现在我回头看。谢谢你的帮助。你认为我应该担心另一个错误吗?到目前为止,它似乎还没有产生任何负面影响。
  • 第二个错误是关于 tensorflow 未找到正确的 cuda 安装的警告(请参阅 *.com/questions/59823283/… )如果此安装未完成 GPU 加速将无法正常运行。如果您没有 GPU(或需要加速),它将回退到 CPU 上进行计算。

标签: python tensorflow machine-learning keras computer-vision


【解决方案1】:

【讨论】: