当前位置:   article > 正文

使用cv2.imencode/imdecode+np.tofile/np.fromfile解决python中OpenCV cv2.imread/imwrite无法读取、保存带中文字符路径的图像的问题

cv2.imencode

使用cv2.imencode/imdecode+np.tofile/np.fromfile解决python中OpenCV cv2.imread/imwrite无法读取、保存带中文字符路径的图像的问题

问题描述

OpenCV库在python中的安装、使用非常简单,仅需要pip install opencv-python即可;
然而调用cv2.imread()读取图像或调用cv2.imwrite()保存图像时,若路径字符串中含有中文字符,则无法成功读取、保存图像。

解决方法:使用numpy的tofile和fromfile来完成图像数据的读取和保存

由于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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

imdecode是解码函数,将内存中的二进制buffer数据解码为图像数据;
imencode是编码函数,将图像数据编码为二进制,返回内存中的buffer数据指针;
它们支持与imread和imwrite相同的读写选项(flags,如灰度读取等)。它们的原型如下:

cv.imdecode(buf, flags)->retval
cv.imdecode(ext, buf, flags)->retval, buf
  • 1
  • 2

这两个函数仅在内存中操作数据;而要与硬盘打交道,需要用到np.fromfile()np.tofile()。它们分别是numpy读取/保存数组数据的函数,支持含中文字符的路径。这样就避免了直接调用cv2.imreadcv2.imwrite、不必让OpenCV跟硬盘打交道。

官方文档——关于图像读写

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/857748
推荐阅读
相关标签
  

闽ICP备14008679号