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

查看:87
本文介绍了如何从具有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.我已经用记事本++验证过.

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

在Process Monitor中,我看到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天全站免登陆