How to access image pixel OpenCV

Hi everybody,

hope you are safe and fine. I’m sorry to bother you, but I am experiencing some problems while trying to access a pixel of an image using OpenCV and Python in RDS.
I want to read the pixels of a map.pgm file that I’ve imported in the code as

map_img=cv2.imread('path',cv2.IMREAD_GRAYSCALE)

but when I try to acces the pixel as map_img[i,j] I get this error

> TypeError: 'NoneType' object has no attribute '__getitem__'

Since I checked that the way to access the pixel is correct, I think that the type of error suggests that there may be some problems in the read procedure of the image, but I don’t get any error regarding it from the console.
Thanks for the help,

Cosimo

Hi @cosimo96,

Did you actually change 'path' in your code above to a real image path? This error means that map_img is None, meaning that no image was read, perhaps because you did not specify a valid image path. A valid path could be /home/user/images/your_image.jpg.

1 Like

Hi @bayodesegun,

thanks for your help, I’ve just solved the problem. It was actually regarding the path that I put in the cv2.imread(). The path per se was correct, but I found out that I should have written an r in front of it (e.g. r'/home/user/images/my_img.jpg'). It came out to my mind because I had already used paths to read a txt file without any problems, and doing it I had used this syntax.
Thanks again, have a nice day.

Cosimo

1 Like