pythonopencvpathdiacriticsos.path

cv2.imread file with accent (unicode)


I am trying to load the following file: 'data/chapter_1/capd_yard_signs\\Dueñas_2020.png'

But when I do so, cv2.imread returns an error: imread_('data/chapter_1/capd_yard_signs\Due├▒as_2020.png'): can't open/read file: check file path/integrity load file

When I specified the file name with os.path.join, I tried encoding and decoding the file

f = os.path.join("data/chapter_1/capd_yard_signs", filename.encode().decode())

But that didn't solve the problem.

What am I missing?


Solution

  • This shall work:

    import cv2, numpy as np
    
    pic = cv2.imdecode(np.fromfile(os.path.join("data/chapter_1/capd_yard_signs", filename).replace('\\','/'), dtype=np.uint8), 0)
    

    np.fromfile reads the non-ASCII characters first, .replace('\\','/') should also solve your nonuniform / and \ issue. Then imdecode does its work.

    Here it is for grayscale. For colour, replace 0 with cv2.IMREAD_COLOR.