To demonstrate a NoneType error in action I decided to create a highly simplified Python + OpenCV script that represents what you might see elsewhere on the PyImageSearch blog.
Open up a new file, name it display_image.py , and insert the following code:
→ Launch Jupyter Notebook on Google Colab
→ Launch Jupyter Notebook on Google Colab
OpenCV: Resolving NoneType errors
# import the necessary packages
import argparse
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to the image file")
args = vars(ap.parse_args())
# load the image from disk and display the width, height,
# and depth
image = cv2.imread(args["image"])
(h, w, d) = image.shape
print("w: {}, h: {}, d: {}".format(w, h, d))
# show the image
cv2.imshow("Image", image)
cv2.waitKey(0)
All this script does is:
Parse command line arguments.
(Attempts to) load an image from disk.
Prints the width, height, and depth of the image to the terminal.
Displays the image to our screen.
For most Python developers who are familiar with the command line, this script won’t give you any trouble.
But if you’re new to the command line and are unfamiliar/uncomfortable with command line arguments, you can easily run into a NoneType error if you’re not careful.
How, you might say?
The answer lies in not properly using/understanding command line arguments.
Over the past few years of running this blog, I’ve seen many emails and blog post comments from readers who are trying to modify the .add_argument function to supply the path to their image file.
Regards,
Rachel Gomez
|