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

it2022-05-05  114

环境: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() 图片解码和编码)


最新回复(0)