cv2.imread file with accent (unicode)
Question:
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_signsDue├▒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?
Answers:
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
Well…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.)
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_signsDue├▒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?
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
Well…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.)