.npy文件的保存與加載


 1 import os
 2 import numpy as np
 3 import cv2
 4 import matplotlib.pyplot as plt
 5 from PIL import Image
 6 def create_train_data(data_path,file_path,image_rows,image_cols):
 7     train_data_path = os.path.join(data_path, file_path)
 8     images = os.listdir(train_data_path)
 9     image_sorted=sorted(images,key=lambda i:int(i.split('t')[1].split('.')[0]))
10     imgs=[]
11     i = 0
12     print('-'*30)
13     print('Creating training images...')
14     print('-'*30)
15     for image_name in image_sorted:
16         if 'mask' in image_name:
17             continue
18         #image_mask_name = image_name.split('.')[0] + '_mask.tif'#分離得到點之前的內容,即文件名
19 
20         img = cv2.imread(os.path.join(train_data_path,image_name),cv2.IMREAD_GRAYSCALE)#注意,opencv讀取的路徑不能含有中文名
21         img=cv2.resize(img,(image_rows,image_cols))
22         img=np.reshape(img,img.shape+(1,))#(32,32,1)
23         imgs.append(img)
24     imgs_arr=np.array(imgs)
25     # plt.imshow(imgs_arr[10].squeeze())
26     # plt.show()
27     print(imgs_arr.shape)
28     print('Loading done.')
29     np.save(r'G:\data\imgs_arr_train.npy', imgs_arr)
30     #np.save('imgs_mask_train.npy', imgs_mask)
31     print('Saving to .npy files done.')
32 def load_train_data():
33     imgs_train = np.load('imgs_train.npy')
34     imgs_mask_train = np.load('imgs_mask_train.npy')
35     return imgs_train, imgs_mask_train
36 if __name__=='__main__':
37     create_train_data('G:\\data','mnist_test',32,32)

注意,在此期間有幾個小問題需要注意

1.在使用cv2.imread()的時候路徑中不能出現中文路徑否則會報錯TypeError: Image data cannot be converted to float,但是使用PIL.Image.open()讀取的時候路徑可以為中文路徑

2..split()的用法,以指定字符為分隔符,將原始的字符串分割成列表

3.os.rename(old_path,new_path)是替換路徑,os.renames()是既可以替換路徑,也可以替換文件名,但是需要指出的是需要給定新命名的文件的路徑

1 rename
2  for img_old in img_path:
3      img_new='t'+img_old.split('.')[0]+'.jpg'
4      os.chdir(path)#切換至當前路徑,即將rename之后的文件保存在當前路徑下,如#不切換,則需要定義保存路徑
5      os.renames(img_old,img_new)

 


免責聲明!

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



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