赞
踩
OpenCV库在python中的安装、使用非常简单,仅需要pip install opencv-python
即可;
然而调用cv2.imread()
读取图像或调用cv2.imwrite()
保存图像时,若路径字符串中含有中文字符,则无法成功读取、保存图像。
由于numpy库支持包含中文字符的文件路径,因此采取“numpy读写文件二进制内容+OpenCV编码解码”
的模式完成图像读写,见下面的代码示例:
import numpy as np
import cv2
str_img_input = 'D:/测试图像'
str_img_output= 'D:/输出图像'
# 读取图像
img_data = cv2.imread(str_img_input)# 失败,路径包含中文
img_data = cv2.imdecode(np.fromfile(str_img_input), cv2.IMREAD_COLOR)# 成功,先由numpy读取图像文件中的二进制内容,再由opencv解析为RGB彩色图像数据
# 保存图像
cv2.imwrite(str_img_output, img_data)# 失败,路径包含中文
cv2.imencode('.jpg',img_data)[1].tofile(str_img_output)# 成功,按jpg格式编码图像数据后,将二进制数据保存到str_img_output
imdecode
是解码函数,将内存中的二进制buffer数据解码为图像数据;
imencode
是编码函数,将图像数据编码为二进制,返回内存中的buffer数据指针;
它们支持与imread和imwrite相同的读写选项(flags,如灰度读取等)。它们的原型如下:
cv.imdecode(buf, flags)->retval
cv.imdecode(ext, buf, flags)->retval, buf
这两个函数仅在内存中操作数据;而要与硬盘打交道,需要用到np.fromfile()
和np.tofile()
。它们分别是numpy读取/保存数组数据的函数,支持含中文字符的路径。这样就避免了直接调用cv2.imread
和cv2.imwrite
、不必让OpenCV跟硬盘打交道。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。