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]
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)
这可以通过
open()
打开文件,该文件支持链接答案中的Unicode我把它们复制到一个临时目录。这对我来说很好
受Thomas Weller答案的启发,您还可以使用^{} 读取图像并将其转换为ndarray,然后使用
cv2.imdecode()
将数组解码为三维numpy ndarray(假设这是一幅没有alpha通道的彩色图像):np.fromfile()
将磁盘上的映像转换为numpy一维数组表示cv2.imdecode
可以解码此格式并转换为正常的三维图像表示cv2.IMREAD_UNCHANGED
是用于解码的标志。完整的标志列表可以在here中找到PS.有关如何使用unicode字符将图像写入路径,请参见here
相关问题 更多 >
编程相关推荐