Home > Enterprise >  Python AttributeError: 'NoneType' object has no attribute 'shape'
Python AttributeError: 'NoneType' object has no attribute 'shape'

Time:09-22

I have a file named negative.py inside the cselect folder. Why is there an error in vs code when the path I used is

image = cv.imread('images/tooth.jpeg')
height, width, channels = image.shape

The error:

Traceback (most recent call last):
  File "d:\Users\iveej\Desktop\cs\python\cselect\negative.py", line 7, in <module>
    height, width, channels = image.shape
AttributeError: 'NoneType' object has no attribute 'shape'

But when I changed the path to:

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

it's working.

Both work in Pycharm but not in vs code. Why is that? Thank you for answering in advance.

CodePudding user response:

This is a paths issue. When running a script in VS Code the current active folder is not changed to the folder of the script being run. Relative paths are relative to the currently active folder not the folder the script is in. (This may be your project root).

You can either -

  1. use absolute paths
  2. configure VS Code to set execution folder to the same folder as the script
  3. modify your paths relative to VS Code's execution folder, or
  4. change the active folder when your script is run

For 4, you can do something like --

import os

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

This will change the current ative folder to the folder which contains the script.

  • Related