You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用cv2.imread()读取含阿拉伯文路径的JPG图片失败问题排查

问题原因

cv2.imread()对包含非ASCII字符(如阿拉伯文)的文件路径支持存在缺陷,它默认依赖系统本地编码解析路径,遇到复杂非英文字符时会解析失败,返回None;而plt.imread()底层基于PIL/Pillow库,对多语言路径的编码处理更完善,因此能正常读取文件。

解决方法

方法1:读取文件字节流后解码(跨平台通用)

绕开cv2.imread()的路径解析环节,直接读取文件字节,再用cv2.imdecode()解码:

import cv2
import numpy as np

with open(file_path, 'rb') as f:
    # 将文件字节转为numpy数组
    img_byte_arr = np.asarray(bytearray(f.read()), dtype=np.uint8)
    # 解码为图像,cv2.IMREAD_COLOR对应彩色图,也可替换为cv2.IMREAD_UNCHANGED
    img = cv2.imdecode(img_byte_arr, cv2.IMREAD_COLOR)

if img is not None:
    print(img.shape)
else:
    print("图像解码失败")

方法2:Windows系统下使用短路径

利用Windows API获取文件的短路径名(不含特殊字符),再传入cv2.imread():

import cv2
import win32api

# 获取短路径
short_file_path = win32api.GetShortPathName(file_path)
img = cv2.imread(short_file_path)

if img is not None:
    print(img.shape)

方法3:确保路径编码正确(部分场景有效)

在Python3中,显式将路径转为UTF-8编码的字节串(仅部分环境适用):

import cv2

# 转为UTF-8字节路径
img = cv2.imread(file_path.encode('utf-8'))
if img is not None:
    print(img.shape)

注:方法1是最稳定的跨平台解决方案,不受路径字符类型限制。

内容的提问来源于stack exchange,提问作者AAA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:35:17