Python 属性错误:'NoneType'对象没有属性'shape'



我在cselect文件夹中有一个名为negative.py的文件。为什么当我使用的路径是

时,vs code中会出现错误?
image = cv.imread('images/tooth.jpeg')
height, width, channels = image.shape

错误:

Traceback (most recent call last):
File "d:UsersiveejDesktopcspythoncselectnegative.py", line 7, in <module>
height, width, channels = image.shape
AttributeError: 'NoneType' object has no attribute 'shape'

但是当我把路径改为:

image = cv.imread('D:\Users\iveej\Desktop\cs\python\cselect\images\tooth.jpeg')

都可以在Pycharm中工作,但不能在vs code中工作。为什么呢?谢谢你提前回答。

这是一个路径问题。当在VS Code中运行脚本时,当前活动文件夹不会更改为正在运行的脚本的文件夹。相对路径相对于当前活动的文件夹,而不是脚本所在的文件夹。(这可能是你的项目根目录)。

你可以选择-

  1. 使用绝对路径
  2. 配置VS Code将执行文件夹设置为与脚本相同的文件夹
  3. 相对VS Code的执行文件夹修改路径,或者
  4. 在脚本运行时更改活动文件夹

对于4,您可以这样做——

import os
path = os.path.dirname(os.path.abspath(__file__))
os.chdir(path)

这将把当前执行的文件夹更改为包含脚本的文件夹。

最新更新