解决 OpenCV cv2.imread()、cv2.imwrite()函数无法读取、写入以中文命名的图像文件及含有中文路径的图像文件

环境:Windows10、Python3.6、OpenCV3.3
问题
OpenCV 函数cv2.imread()、cv2.imwrite()在读取含有中文路径及以中文命名的文件时,会报错,主要原因是因为cv2.imread()、cv2.imwrite()不支持中文。

代码及出错代码

import cv2
img = cv2.imread(r"G:\Python_work\图片\vikings.jpg")
cv2.imshow("img",img)
cv2.waitKey()
cv2.destroyAllWindows()

报错
OpenCV(3.4.1) Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow, file D:\Build\OpenCV\opencv-3.4.1\modules\highgui\src\window.cpp, line 364
Traceback (most recent call last):
File “G:/Python_work/test/test2.py”, line 5, in
cv2.imshow(“img”,img)
cv2.error: OpenCV(3.4.1) D:\Build\OpenCV\opencv-3.4.1\modules\highgui\src\window.cpp:364: error: (-215) size.width>0 && size.height>0 in function cv::imshow

解决方法:

OpenCV cv2.imdecode()、cv2.imencode()方法可以解决。

  import cv2
    import numpy as np
    img_path = r"G:\Python_work\图片\vikings.jpg"
    #img = cv2.imread(r"G:\Python_work\图片\vikings.jpg")
    img = cv2.imdecode(np.fromfile(img_path,dtype=np.uint8),cv2.IMREAD_UNCHANGED)
    #也可以写成cv2.imdecode(np.fromfile(img_path,dtype=np.uint8),-1);
    # cv2.IMREAD_UNCHANGED参数可以用-1代替
    #cv2.IMREAD_GRAYSCALE:以灰度模式读入图像:其值为0
    #cv2.IMREAD_COLOR:读入彩色图像:其值为1;
    #np.fromfile()函数相对应的函数为np.tofile()
    img_write = cv2.imencode(".jpg",img)[1].tofile(img_path)
    #cv2.imencode()函数返回两个值;写入成功返回Ture,另一个值为数组.
    #_,im_encode = cv2.imencode(".jpg",img)
    cv2.imshow("img",img)
    cv2.waitKey()
    cv2.destroyAllWindows()

其中 cv2.imwrite() 的解决方法为:

cv2.imwrite(imagepath, frame)

修改为

cv2.imencode('.jpg', frame)[1].tofile(imagepath)

参考链接:

https://blog.csdn.net/kebu12345678/article/details/54837245(NumPy 文件存取 tofile,fromfile, load,save);

https://blog.csdn.net/dcrmg/article/details/79155233(OpenCV-Python cv2.imdecode()和cv2.imencode() 图片解码和编码)

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值