Search code examples
pythonopencvnumpymatplotlibimage-compression

AttributeError: 'NoneType' object has no attribute 'ravel'


Can someone please tell me what is wrong with this code? I keep on getting a NoneType error. I am trying to create a histogram.

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('C:\Pictures\naturalScene.bmp',0)
plt.hist(img.ravel(),256,[0,256]);
plt.show()

Solution

  • From the docs:

    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 ).

    Your path is incorrect you need to escape the \n:

    cv2.imread('C:\\Pictures\\naturalScene.bmp',0)
    

    Or use /:

    cv2.imread('C:/Pictures/naturalScene.bmp',0)
    

    Or as @Martijn Pieters commented use a raw string literal:

    cv2.imread(r'C:\Pictures\naturalScene.bmp',0)