OpenCv imwrite not working due to special character in file path

I cannot save the image when the file path has a special character (like "é").

Here's a test from the 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 this?

Thank!

EDIT:

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

So I am using @ 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)

      

+4


source to share


4 answers


Try to code 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 read user @ PM's answer according to your utf-16 windows:

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

      

If that doesn't work, 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)

      

+2


source


if you are using windows then this problem occurs because there is no filename with special character in windows. I run into this too. this works better with linux.



0


source


Coding problems .... difficult but not impossible

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

You can encode as Windows character encoding 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 have a readable and usable filename, you can use some library to read your pathnames and then change the encoding ->

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

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

0


source


You can first encode the image with OpenCV and then save it using the numpy method tofile()

, since the encoded image is a solid color numpy ndarray :)

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

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

      

0


source







All Articles