Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 212
TeeVy Avatar asked Jun 02 '17 13:06

TeeVy


3 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')
like image 164
jdhao Avatar answered Oct 13 '22 23:10

jdhao


Try encoding with:

cv2.imwrite('gel/ééé/test.jpg'.encode('utf-8'), frame) # or just .encode(), 'utf-8' is the default

If you are using windows, maybe with:

cv2.imwrite("gel/ééé/test.jpg".encode("windows-1252"), frame)

Or now reading the @PM user answer, according your utf-16 windows:

cv2.imwrite("gel/ééé/test.jpg".encode('UTF-16LE'), frame)

if non of that works to you, try this:

ascii_printable = set(chr(i) for i in range(0x20, 0x7f))

def convert(ch):
    if ch in ascii_printable:
        return ch
    ix = ord(ch)
    if ix < 0x100:
        return '\\x%02x' % ix
    elif ix < 0x10000:
        return '\\u%04x' % ix
    return '\\U%08x' % ix

path = 'gel/ééé/test.jpg'

converted_path = ''.join(convert(ch) for ch in 'gel/ééé/test.jpg')

cv2.imwrite(converted_path, frame)
like image 44
A Monad is a Monoid Avatar answered Oct 13 '22 22:10

A Monad is a Monoid


In one line.

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

like image 33
Ramius Avatar answered Oct 13 '22 22:10

Ramius