cv2.imread() 路径含有中文读取图片失败解决方案

先从一个简单的图片显示程序开始,代码如下:

import cv2


def main():
    img = cv2.imread(r"C:\Users\HP\Desktop\SailorMoon.jpg")
    cv2.imshow('image', img)
    cv2.waitKey(0)


if __name__ == '__main__':
    main()

执行结果如图:
cv2.imread() 路径含有中文读取图片失败解决方案

但是一开始图片名称输入为中文:

import cv2


def main():
    img = cv2.imread(r"C:\Users\HP\Desktop\水冰月.jpg")
    cv2.imshow('image', img)
    cv2.waitKey(0)


if __name__ == '__main__':
    main()

执行结果报错如下:

C:\Users\HP\bishi\Scripts\python.exe D:/PycharmProject/shain_project/CV2.py
Traceback (most recent call last):
  File "D:/PycharmProject/shain_project/CV2.py", line 11, in <module>
    main()
  File "D:/PycharmProject/shain_project/CV2.py", line 6, in main
    cv2.imshow('image', img)
cv2.error: OpenCV(3.4.6) D:\Build\OpenCV\opencv-3.4.6\modules\highgui\src\window.cpp:366: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

读取图片时发生异常,一切都是中文路径惹的祸,编程还是一切以英文为主比较好,免得出错。解决方法如下:

import cv2 
import numpy as np

def main():
    img=cv2.imdecode(np.fromfile(r"C:\Users\HP\Desktop\水冰月.jpg",dtype=np.uint8),-1)
    cv2.imshow('image',img)
    cv2.waitKey(0)  

if __name__ == '__main__':
    main()

完美运行,图片成功显示,借助于 numpy 来读入数据,然后 cv2.imdecode()把数据转换 (解码) 成图像。