如何使用Unicode字符从路径读取图像?

31

我有以下代码,但因为无法从磁盘读取文件而失败。图像始终为None

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

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

注意:我的文件已经保存为带有BOM的UTF-8格式。我用Notepad++进行了验证。

在Process Monitor中,我发现Python正在从错误的路径访问该文件:

Process Monitor

我已经阅读了以下内容:

6个回答

41

可以通过以下步骤完成:

  • 使用支持Unicode的open()打开文件,
  • 将内容读取为字节数组,
  • 将字节数组转换为NumPy数组,
  • 解码图像。
# -*- 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)

5
谢谢,这解决了我找不到的错误。我一直在使用os.path.isfile(myPath)来检查文件是否存在,然后用cv2.imread打开它,但它总是显示为“None”对象!非常愤怒。你的解决方案解决了我的问题。谢谢。 - Endyd
3
只需使用cv2.imdecode(np.fromfile(u'D:\\ö\\handschuh.jpg', np.uint8), cv2.IMREAD_UNCHANGED)即可。 - jdhao

31
受Thomas Weller回答的启发,您还可以使用np.fromfile()来读取图像并将其转换为ndarray,然后使用cv2.imdecode()将数组解码为三维numpy ndarray(假设这是一张没有alpha通道的彩色图像):
import numpy as np

# img is in BGR format if the underlying image is a color image
img = cv2.imdecode(np.fromfile('测试目录/test.jpg', dtype=np.uint8), cv2.IMREAD_UNCHANGED)

np.fromfile() 将磁盘上的图像转换为 numpy 一维 ndrray 表示形式。cv2.imdecode 可以解码此格式并将其转换为常规的三维图像表示形式。 cv2.IMREAD_UNCHANGED 是用于解码的标志。完整的标志列表可以在这里找到。

PS. 如何将图像写入具有 Unicode 字符的路径,请参见这里


1

我将它们复制到一个临时目录。对我来说运行良好。

import os
import shutil
import tempfile

import cv2


def cv_read(path, *args):
    """
    Read from a path with Unicode characters.

    :param path: path of a single image or a directory which contains images
    :param args: other args passed to cv2.imread
    :return: a single image or a list of images
    """
    with tempfile.TemporaryDirectory() as tmp_dir:
        if os.path.isdir(path):
            shutil.copytree(path, tmp_dir, dirs_exist_ok=True)
        elif os.path.isfile(path):
            shutil.copy(path, tmp_dir)
        else:
            raise FileNotFoundError

        img_arr = [
            cv2.imread(os.path.join(tmp_dir, img), *args)
            for img in os.listdir(tmp_dir)
        ]

        return img_arr if os.path.isdir(path) else img_arr[0]

0

可以通过以下步骤完成:

  1. 保存当前目录
  2. 将当前目录更改为需要保存图像的目录
  3. 保存图像
  4. 将当前目录更改为第一步保存的目录
import os
from pathlib import Path
import cv2

im_path = Path(u'D:\\ö\\handschuh.jpg')

# Save current directory
curr_dir = os.getcwd()
# change current directory to the one the image must be saved
os.chdir(im_path.parent)
# read the image
bgrImage = cv2.imread(im_path.name)
# change current directory to the one saved in step 1
os.chdir(curr_dir)

-1

我的问题和你的类似,不过我的程序将在image = cv2.imread(filename)语句处终止。

我通过先将文件名编码为utf-8,然后解码来解决这个问题。

 image = cv2.imread(filename.encode('utf-8', 'surrogateescape').decode('utf-8', 'surrogateescape'))

-5
bgrImage = cv2.imread(filename.encode('utf-8'))

将文件完整路径编码为 utf-8


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接