python3中OpenCV imwrite保存中文路径文件

原先一段将特征值保存为图片的代码,这部分学生的电脑上运行没有生成图片

代码的基本样子是:

 1 import os
 2 import cv2
 3 import numpy as np
 4 
 5 
 6 def text_to_pic(file):
 7     f = open(file)
 8     all_features = f.read().strip().split(' ')
 9     all_features = np.array(all_features)
10     all_features = all_features.astype(np.float)
11     all_features = all_features.reshape((160 * 160, 3))
12     all_features = all_features[:, [2, 1, 0]]
13     all_features = all_features.reshape((160, 160, 3))
14     file_save = file.replace('.txt', '.jpg')
15     cv2.imwrite(file_save, all_features)
16 
17 
18 if __name__ == '__main__':
19     for root, dirs, files in os.walk('C:\\Users\\Administrator\\Desktop\\image', topdown=False):
20         for name in files:
21             text_to_pic(os.path.join(root, name))

 

 

学生将自己的代码传过来之后,只修改了19行的路径,完全没有问题,说明代码基本功能没有问题,区别就是环境了

然后远程学生的设备,发现这D盘下新建一个test文件夹,程序也是正常运行的,这说明基本环境也没有问题

然后发现学生是将原先的特征文本放在桌面,而用户名为xxx(学生本人姓名),然后就怀疑可能是由于路径含有中文

使用cv2.imshow查看了一下,能正常显示图片,说明图片是正常读取了

然后尝试了几种修改编码的方法,发现都不起作用

最后以"cv2.imwrite 中文"为关键字搜索,发现python3的OpenCV保存图片,如果要存中文路径,需要用imencode tofile方法操作

代码将15句改为

cv2.imencode('.jpg', all_features)[1].tofile(file_save)

问题解决

posted @ 2019-05-26 21:52  朋克  阅读(7716)  评论(0编辑  收藏  举报