python-opencv读写图像中文路径的问题
在使用python的opencv库处理图像时,通常使用cv2.imread()函数读取图像,然而如果图像路径包含中文,则会读取失败。对此,需要作以下修改,即可读取中文路径的图像。
cv2.imwrite(filename, img)
修改为
cv2.imencode('.jpg', img)[1].tofile(filename)
cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
修改为
cv2.imdecode(np.fromfile(filename, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
将其封装成函数并调用,如下所示:
import cv2
import numpy as np
def cv_imread_u8(file_path, flag=-1):
cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), flag)
return cv_img
def cv_imwrite(filename, img):
cv2.imencode('.jpg', img)[1].tofile(filename)
filepath = r'D:\MATLAB_m\0图像降噪\girl.png'
img = cv_imread_u8(filepath)
cv_imwrite(r'D:\保存结果\dst.png', img)