OpenCv imwrite doesn't work because of special character in file path

Viewed 5079

I can't save an image when the file path has special character (like "é" for example).

Here is a test from Python 3 shell :

>>> cv2.imwrite('gel/test.jpg', frame)
True
>>> cv2.imwrite('gel/ééé/test.jpg', frame)
False
>>> cv2.imwrite('gel/eee/test.jpg', frame)
True

Any ideas how to do it?

Thanks!

EDIT :

Unfortunately, all suggestions proposed by @PM2Ring and @DamianLattenero don't seem to work :(

So, I use the @cdarke's solution, here's my final code :

destination = 'gel/ééé/'
gel = 'test.jpg'
script_path = os.getcwd()
os.chdir(destination)
cv2.imwrite(gel, frame)
os.chdir(script_path)
5 Answers

You can first encode the image with OpenCV and then save it with numpy tofile() method since the encoded image is a one-dim numpy ndarray:

is_success, im_buf_arr = cv2.imencode(".jpg", frame)

im_buf_arr.tofile('gel/ééé/test.jpg')

In one line.

cv2.imencode(".jpg",frame)[1].tofile("gel/ééé/test.jpg")

Encoding issues.... difficult but no impossible

if you have this string = 'テスト/abc.jpg'

You can encode as Windows encoding the characters like this->

print('テスト/abc.jpg'.encode('utf-8').decode('unicode-escape'))

And you get something like this = 'ãã¹ã/abc.jpg'

Then if you want to read the file and get the filenames readable and usable, you can use some library to read the filenames of your path and then change the encoding->

#fname is like 'ãã¹ã/abc.jpg'

fname.encode('iso-8859-1').decode('utf-8')) # This result of your initial string ='テスト/abc.jpg'

These are my functions for both writing and reading:

def read_image(path):
    return cv2.imdecode(np.fromfile(path,dtype=np.uint8), -1)

def save_image(img, path):
    cv2.imencode(".png", img)[1].tofile(path+'/your_file_name.png')
Related