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)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
From the cv2.imread() documentation:
The function
imreadloads 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.
尽可能使用绝对路径加载文件。如果您需要从与脚本相同的目录加载它,请使用脚本文件名作为起点:
import os.path
# construct an absolute path to the directory this file is located in
HERE = os.path.dirname(os.path.abspath(__file__))
Run Code Online (Sandbox Code Playgroud)
然后使用它作为加载文件的起点:
image_path = os.path.join(HERE, 'freelancer.jpg')
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
Run Code Online (Sandbox Code Playgroud)
如果可能无法加载图像(假设用户将文件传递到您的脚本),请测试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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15840 次 |
| 最近记录: |