Reputation: 1211
I am new to opencv and I am trying to print the pixels.
import numpy as np
import cv2
img = cv2.imread('freelancer.jpg',cv2.IMREAD_COLOR)
px = img[55,55]
print(px)
I am getting
Traceback (most recent call last):
File "C:/Users/Jeet Chatterjee/image processing/basic_image_op.py", line 6, in <module>
px = img[55,55]
TypeError: 'NoneType' object is not subscriptable
Upvotes: 3
Views: 16479
Reputation: 1123350
From the cv2.imread()
documentation:
The function
imread
loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix (Mat::data==NULL
)
The documentation tends to be geared towards the C++ API, but for Python, read returns None
for the latter case.
So what happened is that your image file could not be read; it is either missing, has improper permissions or is in an unsupported or invalid format.
Given that you are using a relative path to load the file, I'd say it is missing. Missing from the current working directory, which is not the same thing as the directory you put the script in.
Use an absolute path to load files when possible. If you need to load it from the same directory as the script, use the script filename as a starting point:
import os.path
# construct an absolute path to the directory this file is located in
HERE = os.path.dirname(os.path.abspath(__file__))
then use that as a starting point to load the file:
image_path = os.path.join(HERE, 'freelancer.jpg')
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
If not being able to load the image is a possibility (say a user passed in the file to your script), test for None
:
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
if img is None:
print("Can't load image, please check the path", file=sys.stderr)
sys.exit(1)
Upvotes: 6