Python读取中文路径,出现乱码问题解决方案

Python读取中文路径,出现乱码问题解决方案

欢迎学习交流!
邮箱: z...@1...6.com
网站: https://zephyrhours.github.io/

一、问题描述

笔者在使用opencv读取带有中文路径的图片时,发现会出现乱码的情况。具体问题如下:

python 复制代码
# 读取带有中文路径的图片出现错误
import cv2

img_path = r'C:\Users\zephy\Documents\Python\CSDN\测试 图片\图片1.jpg'
img = cv2.imread(img_path, cv2.IMREAD_COLOR)

cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

当读取的文件路径出现中文时,(文件夹名为中文或者文件为中文)出现如下错误:

WARN:0@0.024\] global loadsave.cpp:241 cv::findDecoder imread_('C:\\Users\\zephy\\Documents\\Python\\CSDN\\测试 图片\\图片1.jpg'): can't open/read file: check file path/integrity Traceback (most recent call last): File "C:\\Users\\zephy\\Documents\\Python\\CSDN\\demo.py", line 8, in cv2.imshow("image", img) cv2.error: OpenCV(4.10.0) D:\\a\\opencv-python\\opencv-python\\opencv\\modules\\highgui\\src\\window.cpp:973: error: (-215:Assertion failed) size.width\>0 \&\& size.height\>0 in function 'cv::imshow' ![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/93ff372fe558491c8d4ac7c9783f32c7.png) 在定位问题时,将读取图片路径和图片名词更换为全英文后,发现可以正常读取,具体如下:

python 复制代码
# 读取英文路径下的图片,显示正常
import cv2

img_path = r'C:\Users\zephy\Documents\Python\CSDN\caps.bmp'
img = cv2.imread(img_path, cv2.IMREAD_COLOR)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

二、问题解决

定位问题后,发现出现上述错误的原因是在中文路径的编解码上,下面是笔者在查找相关文献后找到的解决方法,具体代码如下:

python 复制代码
import cv2
import numpy as np

img_path = r'C:\Users\zephy\Documents\Python\CSDN\测试 图片\图片1.jpg'
img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)  # 替换cv2.imread(img_path, cv2.IMREAD_COLOR)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

运行代码,可顺利读取带有中文路径或中文名词的图片,问题解决。具体读取图片如下:

相关推荐
码农水水4 分钟前
国家电网Java面试被问:二叉树的前序、中序、后序遍历
java·开发语言·面试
Respect@8 分钟前
qml之TableViewColumn
开发语言·qml
股朋公式网15 分钟前
斩仙飞刀、 通达信飞刀 源码
python·算法
不吃橘子的橘猫15 分钟前
NVIDIA DLI 《Build a Deep Research Agent》学习笔记
开发语言·数据库·笔记·python·学习·算法·ai
算法与双吉汉堡19 分钟前
【短链接项目笔记】6 短链接跳转
java·开发语言·笔记·后端·springboot
学Linux的语莫20 分钟前
python的基础使用
开发语言·python
万粉变现经纪人29 分钟前
如何解决 pip install SSL 报错 ValueError: check_hostname requires server_hostname 问题
网络·python·网络协议·beautifulsoup·bug·ssl·pip
逻极31 分钟前
FastAPI + SQLAlchemy 现代API项目实战:从零到上手的Python MySQL开发指南
python·mysql·fastapi·异步·sqlalchemy
wildlily842734 分钟前
C++ Primer 第5版章节题 第十章
开发语言·c++
吃人陈乐游刘35 分钟前
06实战经验X-anylabelingAI自动标注数据集-本地实现-方法二(2025年12月)保姆级教程
python·miniforge·xanylabeling