如何从带有Unicode字符的路径读取图像?

2024-04-23 22:45:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

注意:我的文件已与BOM一起保存为UTF-8。我用记事本++进行了验证

在Process Monitor中,我看到Python从错误的路径访问文件:

Process Monitor

我读过:


Tags: 文件代码图像importnumpynonecv2磁盘
3条回答

这可以通过

  • 使用open()打开文件,该文件支持链接答案中的Unicode
  • 以字节数组的形式读取内容
  • 将字节数组转换为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)

我把它们复制到一个临时目录。这对我来说很好

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]

受Thomas Weller答案的启发,您还可以使用^{}读取图像并将其转换为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一维数组表示cv2.imdecode可以解码此格式并转换为正常的三维图像表示cv2.IMREAD_UNCHANGED是用于解码的标志。完整的标志列表可以在here中找到

PS.有关如何使用unicode字符将图像写入路径,请参见here

相关问题 更多 >