opencv-python imread不支持中文路径的解决方法
opencv
OpenCV: 开源计算机视觉库
项目地址:https://gitcode.com/gh_mirrors/opencv31/opencv
·
opencv 库中 imread 用来读取图片文件,但是这个不支持中文路径。
中文路径的话,需要用 imdecode 方法。
1、读取带中文的图片
imdecode和imread读取图片,都是以bgr的方式来读取。opencv进行图像处理,也是bgr。
网上看到有人说imdecode读取图片是rgb,使用opencv进行图像处理的时候需要做一下转换(rgb转成bgr);
但是我自己测了一下,其实是bgr方式。
# 读取带中文的图片,bgr
def cv_imread(file_path):
cv_img = cv.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
return cv_img
从网上找的下面这种方法,有问题:
# 报错: 'utf-8' codec can't decode byte 0xb2 in position 24: invalid start byte
def cv_imread2(file_path=""):
file_path_gbk = file_path.encode('gbk') # unicode转gbk,字符串变为字节数组
img_mat = cv.imread(file_path_gbk.decode()) # 字节数组直接转字符串,不解码
return img_mat
2、验证 imdecode 以 bgr 存储
众所周知,cv2.imread 是以 bgr 方式存储,故此处用cv2.imread做对比,看最终的BGR的灰度值就知道。
# cv.imdecode 和 cv.imread,读图都是bgr方式。以下可证明两者方式一样。
img = cv_imread("./彩色图像.tiff")
B, G, R = cv.split(img)
img2 = cv.imread("./color.tiff")
B2, G2, R2 = cv.split(img2) # 拆分通道,opencv存储图片是bgr方式
3、保存带中文的图片
# 保存带中文的图片
def cv_imwrite(file_path):
cv.imencode('.tiff', img)[1].tofile(out_path) # 保存带中文的图片,opencv保存的tiff,默认是lzw压缩
4、调用
if __name__ == "__main__":
img = cv_imread("./彩色图像.tiff")
# cv.namedWindow('ReadImgCN', cv.WINDOW_AUTOSIZE) # 图片太大,不采用自适应
cv.namedWindow('ReadImgCN', cv.WINDOW_NORMAL)
cv.resizeWindow('ReadImgCN', 1000, 1000)
cv.imshow("ReadImgCN", img)
cv.waitKey(0)
cv.destroyAllWindows()
out_path = './测试.tiff'
cv_imwrite(out_path)
附录
OpenCV: 开源计算机视觉库
最近提交(Master分支:2 个月前 )
386be68f
Fix alpha handling for blending in PNG format #27981
### Pull Request Readiness Checklist
closes #27974
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
11 小时前
87436149
Fix #27968: Eliminate unnecessary type conversions in GrabCut initGMMs 12 小时前
新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐


所有评论(0)