Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve the TypeError: 'NoneType' object is not subscriptable in opencv (cv2 Python)

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
like image 421
Mandrek Avatar asked Apr 07 '26 02:04

Mandrek


1 Answers

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)
like image 164
Martijn Pieters Avatar answered Apr 10 '26 03:04

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!