爲了獲取大量的圖片訓練數據,在採集數據的過程當中經常使用視頻的方式採集數據,但對於深度學習,訓練的過程須要不少的有有標籤的數據,這篇文章主要是解決視頻文件轉換成圖片文件,並加標籤,最後把數據存儲到pkl文件中,爲後續深度學習提供數據。python
# 導入所須要的庫 import cv2 import numpy as np
# 定義保存圖片函數 # image:要保存的圖片名字 # addr;圖片地址與相片名字的前部分 # num: 相片,名字的後綴。int 類型 def save_image(image,addr,num): address = addr + str(num)+ '.jpg' cv2.imwrite(address,image)
# 讀取視頻文件 videoCapture = cv2.VideoCapture("./input/chen6.30.mp4") # 經過攝像頭的方式 # videoCapture=cv2.VideoCapture(1)
#讀幀 success, frame = videoCapture.read() i = 0 while success : i = i + 1 save_image(frame,'./output/img_',i) if success: print('save image:',i) success, frame = videoCapture.read()
save image: 1 save image: 2 save image: 3 save image: 4 save image: 5 save image: 6......
import numpy as np from PIL import Image import pickle import matplotlib.pyplot as plt %matplotlib inline
img_640 = Image.open('./output/img_640.jpg') img_910 = Image.open('./output/img_910.jpg')
# 顯示圖片 plt.imshow(img_640)
<matplotlib.image.AxesImage at 0x15ece1330b8>
img_640_n = np.array(img_640) img_910_n = np.array(img_910)
type(img_640_n)
numpy.ndarray
# 建立一個空list,用於存儲圖像數據由於是兩張圖片說以建立2個(480, 640, 3)的矩陣。 image_data = []
# 把數據存放進來 image_data.append(img_640_n) image_data.append(imgh_910_n)
# 添加標籤,假設這兩張圖片是兩個類別,把他們標註爲類型1和2 image_data_label = np.empty(2) image_data_label[0] = 1 image_data_label[1] = 2
# 把標籤的類型轉換成int類型,爲了方便出來也把data轉換成numpy.ndarray類型 image_data = np.array(image_data) image_data_label=image_data_label.astype(np.int) image_data_label
array([1, 2])
plt.imshow(image_data[1])
<matplotlib.image.AxesImage at 0x15ece1845f8>
# 把數據合併成一個元組進行保存 train_data = (image_data,image_data_label)
# 把數據寫入pkl文件中 write_file=open('./input/train_data.pkl','wb') pickle.dump(train_data,write_file) write_file.close()
# 從pkl文件中讀取圖片數據和標籤 read_file=open('./input/train_data.pkl','rb') (train_data,lab_data)=pickle.load(read_file) read_file.close()
# 查看讀取出來的數據 train_data.shape
(2, 480, 640, 3)
lab_data
array([1, 2])
plt.imshow(train_data[0])
<matplotlib.image.AxesImage at 0x15ece1daa20>
到這裏就完成了把圖片加標籤後存儲與讀取,爲後續神經網絡數據的輸入作準備,當咱們須要數據的時候,把pkl文件加載進來就能夠。git
github地址github