Python – 解决opencv-python使用cv2.imwrite()保存中文路径图片失败的问题
![](https://img-blog.csdnimg.cn/img_convert/8f26482ef8a776a0e2986fc56567916e.png)
StubbornHuang
11月前
1 解决opencv-python使用cv2.imwrite()保存中文路径图片失败的问题
一般情况下,使用opencv-python库保存数据为图片一般会使用以下代码,
import cv2
import numpy as np
def read_image(img_path):
img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
return img
def save_image(img_path,img):
cv2.imwrite(img_path, img)
if __name__ == '__main__':
src_img = read_image('E:\\猫狗数据集\\1.png')
dst_dir = 'E:\\猫狗数据集复制\\'
save_image(dst_dir,src_img)
但是cv2.imwrite
在保存含有中文路径的图片数据时会出错,图片并没有保存成功。在保存含有中文路径的图片时为了避免出错,一般会使用以下代码,
import cv2
import numpy as np
def read_image(img_path):
img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), cv2.IMREAD_COLOR)
return img
def save_image(img_path,img):
cv2.imencode('.png', img)[1].tofile(img_path)
if __name__ == '__main__':
src_img = read_image('E:\\猫狗数据集\\1.png')
dst_dir = 'E:\\猫狗数据集复制\\'
save_image(dst_dir,src_img)
在上述代码中使用cv2.imencode
替换cv2.imwrite
用于含中文路径图片保存。
代码:cv2.imwrite, OpenCV, opencv_python, Python, 中文路径