0

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?

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36

2 Answers2

1

This is how I ended up getting it to work:

from PIL import Image
pil = Image.open(f).convert('RGB') # load the image with pillow and make sure it is in RGB
pilCv = np.array(pil) # convert  the image to an array
img = pilCv[:,:,::-1].copy() # convert the array to be in BGR
  • 2
    Seems rather pointless pulling in yet another dependency, when you already have OpenCV, numpy and Python standard libraries available, that provide several ways to accomplish this. e.g. `cv2.imdecode(np.fromfile('foo.png', dtype=np.uint8), cv2.IMREAD_UNCHANGED)` – Dan Mašek Nov 14 '22 at 16:18
0

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.

Ania Warzecha
  • 1,796
  • 13
  • 26
Sissel Ng
  • 1
  • 2