OpenCV Python not opening images with imread()

From my experience, file paths that are too long (OS dependent) can also cause cv2.imread() to fail.

Also, when it does fail, it often fails silently, so it is hard to even realize that it failed, and usually something further the the code will be what sparks the error.

Hope this helps.


Faced the same problem on Windows: cv.imread returned None when reading jpg files from a subfolder. The same code and folder structure worked on Linux.

Found out that cv.imread processes the same jpg files, if they are in the same folder as the python file.

My workaround:

  • copy the image file to the python file folder
  • use this file in cv.imread
  • remove redundant image file
import os
import shutil
import cv2 as cv

image_dir = os.path.join('path', 'to', 'image')
image_filename = 'image.jpg'
full_image_path = os.path.join(image_dir, image_filename)

image = cv.imread(full_image_path)
if image is None:
    shutil.copy(full_image_path, image_filename)
    image = cv.imread(image_filename)
    os.remove(image_filename)
...

Probably you have problem with special meaning of \ in text - like \t or \n

Use \\ in place of \

imgloc = "F:\\Kyle\\Desktop\\Coinjar\\Test images\\ten.png"

or use prefix r'' (and it will treat it as raw text without special codes)

imgloc = r"F:\Kyle\Desktop\Coinjar\Test images\ten.png"

EDIT:

Some modules accept even / like in Linux path

imgloc = "F:/Kyle/Desktop/Coinjar/Test images/ten.png"

Take care to :

  • try imread() with a reliable picture,
  • and the correct path in your context like (see Kyle772 answer). For me either //or \.

I lost a couple of hours trying with 2 images saved from a left click in a browser. As soon as I took a personal camera image, it works fine.

Spyder screen shot

    #context  windows10 / anaconda / python 3.2.0
    import cv2
    print(cv2.__version__) # 3.2.0
    imgloc = "D:/violettes/Software/Central/test.jpg" #this path works fine.  
    # imgloc = "D:\\violettes\\Software\\Central\\test.jpg"   this path works fine also. 
    #imgloc = "D:\violettes\Software\Central\test.jpg" #this path fails.

    img = cv2.imread(imgloc)
    height, width, channels = img.shape
    print (height, width, channels)

python opencv image-loading imread