由于文件路径中的特殊字符,OpenCv imwrite 不起作用

Tee*_*eVy 6 python opencv python-3.x

当文件路径具有特殊字符(例如“é”)时,我无法保存图像。

这是来自 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
Run Code Online (Sandbox Code Playgroud)

任何想法如何做到这一点?

谢谢!

编辑 :

不幸的是,@PM2Ring 和@DamianLattenero 提出的所有建议似乎都不起作用:(

所以,我使用@cdarke 的解决方案,这是我的最终代码:

destination = 'gel/ééé/'
gel = 'test.jpg'
script_path = os.getcwd()
os.chdir(destination)
cv2.imwrite(gel, frame)
os.chdir(script_path)
Run Code Online (Sandbox Code Playgroud)

jdh*_*hao 5

您可以先使用 OpenCV 对图像进行编码,然后使用 numpytofile()方法将其保存,因为编码的图像是一维 numpy ndarray?

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

im_buf_arr.tofile('gel/ééé/test.jpg')
Run Code Online (Sandbox Code Playgroud)


Dam*_*ero 2

尝试使用以下方式进行编码:

\n\n
cv2.imwrite(\'gel/\xc3\xa9\xc3\xa9\xc3\xa9/test.jpg\'.encode(\'utf-8\'), frame) # or just .encode(), \'utf-8\' is the default\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您使用的是 Windows,也许可以使用:

\n\n
cv2.imwrite("gel/\xc3\xa9\xc3\xa9\xc3\xa9/test.jpg".encode("windows-1252"), frame)\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者现在根据您的 utf-16 窗口阅读 @PM 用户答案:

\n\n
cv2.imwrite("gel/\xc3\xa9\xc3\xa9\xc3\xa9/test.jpg".encode(\'UTF-16LE\'), frame)\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果这对您不起作用,请尝试以下操作:

\n\n
ascii_printable = set(chr(i) for i in range(0x20, 0x7f))\n\ndef convert(ch):\n    if ch in ascii_printable:\n        return ch\n    ix = ord(ch)\n    if ix < 0x100:\n        return \'\\\\x%02x\' % ix\n    elif ix < 0x10000:\n        return \'\\\\u%04x\' % ix\n    return \'\\\\U%08x\' % ix\n\npath = \'gel/\xc3\xa9\xc3\xa9\xc3\xa9/test.jpg\'\n\nconverted_path = \'\'.join(convert(ch) for ch in \'gel/\xc3\xa9\xc3\xa9\xc3\xa9/test.jpg\')\n\ncv2.imwrite(converted_path, frame)\n
Run Code Online (Sandbox Code Playgroud)\n