Search code examples
pythonopencvunicodepath

OpenCV doesn't read images from some directories


I'm trying to read a 16-bit grayscale PNG with OpenCV. This image is stored on a network share. When I try to load the image with cv.imread() nothing is returned:

import cv2 as cv
print(img_paths[0])
print(type(img_paths[0]))
print(img_paths[0].exists())
img = cv.imread(img_paths[0].as_posix(), cv.IMREAD_ANYDEPTH)
print(type(img))

>>> M:\path\to\Meß-ID 1\images\img1.png
>>> <class 'pathlib.WindowsPath'>
>>> True
>>> <class 'NoneType'>

As you can see the file certainly exists. It even is loadable with PIL:

from PIL import Image
img = Image.open(img_paths[0])
print(img)

>>> <PIL.PngImagePlugin.PngImageFile image mode=I;16 size=2560x300 at 0x27F77E95940>

And only when I copy the image to the directory of the .ipynb I'm working in, openCV is able to load the image:

import shutil
shutil.copy(img_paths[0], "./test_img.png")
img = cv.imread("./test_img.png", cv.IMREAD_ANYDEPTH)
print(type(img))

>>> <class 'numpy.ndarray'>

Why is OpenCV refusing to load the image?


Solution

  • Yes, OpenCV on Windows has issues with encodings. Usually, anything non-ASCII in the path string can cause you trouble.

    Shortest possible solution:

    im = cv.imdecode(np.fromfile(the_path, dtype=np.uint8), cv.IMREAD_UNCHANGED)