获取Python脚本上不可下标的“非类型”对象以进行数字识别

2024-09-28 03:17:00 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我决定尝试一个数字识别系统,它在从thrMNIST数据库读取时工作,但是当我尝试导入我自己的图像时,我在下面代码段的第二行得到一个错误,说'NoneType' Object Is Not Subscriptable。我已经将cv2作为cv导入,所有正确的导入都在那里,并且已经给出了适当的别名

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

#the neural network setup code

for x in range(1, 6):
    img = cv.imread(f'{x}.png')[:, :, 0]  # where x is the name of the file e.g '5.png'
    img = np.invert(np.array([img]))
    prediction = model.predict(img)
    print(f' The result is probably: {np.argmax(prediction)}')
    plt.imshow(img[0], cmap=plt.cm.binary)
    plt.show()


Tags: the图像import数据库imgpngisas
2条回答

根据docsopencv的imread,如果无法打开图像,则返回None。因此,在您的代码中,您的行为发生了变化:

None[:, :, 0]

因此出现了错误,因为您没有订阅任何内容。因此,您可能想尝试以下无安全性的方法:

for x in range(1, 6):
    img = cv.imread(f'{x}.png')
    if img:
        img = img[:, :, 0]
        img = np.invert(img) # should already be a numpy array
    else:
        print("could not open image")

如果opencv总是以某种方式返回None,您可能需要检查以下问题:cv2.imread always returns NoneType

无法打开该文件,生成None结果。 而是使用原始文件路径。 在此之后,您可能会遇到有关Qt的错误,在这种情况下,请卸载并重新安装Qt和PyQt

for x in range(1, 6):
    img = cv.imread(fr'[file path]\{x}.png')[:, :, 0]  # where x is the name of the file e.g '5.png'
    img = np.invert(np.array([img]))
    prediction = model.predict(img)
    print(f' The result is probably: {np.argmax(prediction)}')
    plt.imshow(img[0], cmap=plt.cm.binary)
    plt.show()

相关问题 更多 >

    热门问题