pythonopencvworking-directory

PyCharm and AttributeError: 'NoneType' object has no attribute 'shape'


I have installed opencv-python and imported cv2. But none of the functions for CV2 is showing up and when I run the code below I get an error that says: "AttributeError: 'NoneType' object has no attribute 'shape'" which is not right.

import argparse
import cv2

# =============================================
# This section is just a path to the image

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")

args = vars(ap.parse_args())
# =============================================
image = cv2.imread(args["image"])
print("width: {} pixels".format(image.shape[1]))
print("height: {} pixels".format(image.shape[0]))
print("channels: {}".format(image.shape[2]))

cv2.imshow("Image", image)
cv2.waitKey(0)

for more info:

  1. I am using pyCharm
  2. Python 3.11
  3. opencv-python 4.7.0.72
  4. OS is Windows 11

Solution

  • AttributeError: 'NoneType' object has no attribute 'shape' doesn't mean that CV2 is not recognized, in fact, it is, otherwise, you would get the error at that line

    cv2.imread(args["image"])
    

    You would get a Cannot find module cv2 error

    AttributeError: 'NoneType' object has no attribute 'shape' means that the object on which you are using the .shape function is Nonetype (ig no object)

    Therefore, it means that your image object ( image = cv2.imread(args["image"]) ) is Nonetype (you should print it to verify)

    A possible reason for that is that args["image"] doesn't return what you expect (a path to the image in your case), you should verify that your path to the image is correct