如何从带有 Unicode 字符的路径中读取图像? [英] How do I read an image from a path with Unicode characters?

查看:10
本文介绍了如何从带有 Unicode 字符的路径中读取图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码但它失败了,因为它无法从磁盘读取文件.图像总是None.

I have the following code and it fails, because it cannot read the file from disk. The image is always None.

# -*- coding: utf-8 -*-
import cv2
import numpy

bgrImage = cv2.imread(u'D:\ö\handschuh.jpg')

注意:我的文件已经保存为带有 BOM 的 UTF-8.我用 Notepad++ 验证过.

Note: my file is already saved as UTF-8 with BOM. I verified with Notepad++.

在进程监视器中,我看到 Python 从错误的路径访问文件:

In Process Monitor, I see that Python is acccessing the file from a wrong path:

我已阅读:

  • Open file with unicode filename, which is about the open() function and not related to OpenCV.
  • How do I read an image file using Python, but that's unrelated to Unicode issues.

推荐答案

可以通过

  • 使用 open() 打开文件,它在链接的答案中支持 Unicode,
  • 将内容读取为字节数组,
  • 将字节数组转换为 NumPy 数组,
  • 解码图像
  • opening the file using open(), which supports Unicode as in the linked answer,
  • read the contents as a byte array,
  • convert the byte array to a NumPy array,
  • decode the image
# -*- coding: utf-8 -*-
import cv2
import numpy

stream = open(u'D:\ö\handschuh.jpg', "rb")
bytes = bytearray(stream.read())
numpyarray = numpy.asarray(bytes, dtype=numpy.uint8)
bgrImage = cv2.imdecode(numpyarray, cv2.IMREAD_UNCHANGED)

这篇关于如何从带有 Unicode 字符的路径中读取图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆