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)

問題解決


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM