首先我事先準(zhǔn)備好五分類的圖片放在對(duì)應(yīng)的文件夾,圖片資源在我的gitee文件夾中鏈接如下:文件管理: 用于存各種數(shù)據(jù)https://gitee.com/xiaoxiaotai/file-management.git
?里面有imgs目錄和npy目錄,imgs就是存放5分類的圖片的目錄,里面有桂花、楓葉、五味子、銀杏、竹葉5種植物,npy目錄存放的是我用這些圖片制作好的npy文件數(shù)據(jù)集,里面有32x32大小和64x64大小的npy文件。
接下來(lái)是數(shù)據(jù)集制作過(guò)程:
首先導(dǎo)入所需的庫(kù)
import os
import cv2
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from mpl_toolkits.axes_grid1 import ImageGrid
%matplotlib inline
import math
from tqdm import tqdm
下面是先顯示本地分類中部分圖片
#先顯示楓葉圖片
folder_path = './datas/imgs/fengye'
# 可視化圖像的個(gè)數(shù)
N = 36
# n 行 n 列
n = math.floor(np.sqrt(N))
images = []
for each_img in os.listdir(folder_path)[:N]:
img_path = os.path.join(folder_path, each_img)
#img_bgr = cv2.imread(img_path)
img_bgr = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), 1) #解決路徑中存在中文的問(wèn)題
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
images.append(img_rgb)
fig = plt.figure(figsize=(6, 8),dpi=80)
grid = ImageGrid(fig, 111, # 類似繪制子圖 subplot(111)
nrows_ncols=(n, n), # 創(chuàng)建 n 行 m 列的 axes 網(wǎng)格
axes_pad=0.02, # 網(wǎng)格間距
share_all=True
)
# 遍歷每張圖像
for ax, im in zip(grid, images):
ax.imshow(im)
ax.axis('off')
plt.tight_layout()
plt.show()
?輸出結(jié)果如下:
?下面是輸出各個(gè)圖片的信息包括圖片寬高、圖片名、所屬類別,os.chdir('../')意思是將當(dāng)前路徑指針指向上一個(gè)目錄,可以用os.getcwd()輸出當(dāng)前所指路徑
# 指定數(shù)據(jù)集路徑
dataset_path = './datas/imgs/'
os.chdir(dataset_path)
print(os.listdir())
df = pd.DataFrame()
for fruit in tqdm(os.listdir()): # 遍歷每個(gè)類別
os.chdir(fruit)
for file in os.listdir(): # 遍歷每張圖像
try:
img = cv2.imread(file)
df = df.append({'類別':fruit, '文件名':file, '圖像寬':img.shape[1], '圖像高':img.shape[0]}, ignore_index=True)
except:
print(os.path.join(fruit, file), '讀取錯(cuò)誤')
os.chdir('../')
os.chdir('../../')
df
輸出結(jié)果如下:
定義標(biāo)簽數(shù)字,因?yàn)閿?shù)據(jù)集標(biāo)簽一般是數(shù)字,訓(xùn)練才更快
# 定義5個(gè)類別的標(biāo)簽
labels = {
'wuweizi': 0,
'fengye': 1,
'guihua': 2,
'zhuye': 3,
'yinxing': 4
}
# 定義訓(xùn)練集和測(cè)試集的比例
train_ratio = 0.8
# 定義一個(gè)空列表用于存儲(chǔ)訓(xùn)練集和測(cè)試集
train_data = []
test_data = []
?數(shù)據(jù)增強(qiáng),我這里是將每一張圖片縮小為64x64,你也可以改成32x32或者其他大小,要注意的是,大小越大數(shù)據(jù)集制作越久,得到的數(shù)據(jù)集大小越大。
# 定義數(shù)據(jù)增強(qiáng)的方法
def data_augmentation(img):
# 隨機(jī)裁剪
img = cv2.resize(img, (256, 256))
x = random.randint(0, 256 - 64)
y = random.randint(0, 256 - 64)
img = img[x:x+64, y:y+64]
# 隨機(jī)翻轉(zhuǎn)
if random.random() < 0.5:
img = cv2.flip(img, 1)
# 隨機(jī)旋轉(zhuǎn)
angle = random.randint(-10, 10)
M = cv2.getRotationMatrix2D((32, 32), angle, 1)
img = cv2.warpAffine(img, M, (64, 64))
return img
# 定義讀取圖片的方法
def read_image(path):
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = data_augmentation(img)
img = img / 255.0
return img
下面是給圖片打上標(biāo)簽了,也就是每一張圖片都給它標(biāo)注屬于哪一種類別(身份),這樣卷積神經(jīng)網(wǎng)絡(luò)就可以在訓(xùn)練的時(shí)候知道類別,從而記住所屬特征的標(biāo)簽值
# 遍歷5個(gè)文件夾,讀取圖片并打上標(biāo)簽
for path, label in labels.items():
files = os.listdir('./datas/imgs/'+path)
random.shuffle(files)
train_files = files[:int(len(files) * train_ratio)]
test_files = files[int(len(files) * train_ratio):]
for file in train_files:
img = read_image(os.path.join('./datas/imgs/'+path, file))
train_data.append((img, label))
for file in test_files:
img = read_image(os.path.join('./datas/imgs/'+path, file))
test_data.append((img, label))
# 工整地輸出每一類別的數(shù)據(jù)個(gè)數(shù)
print('類別:{} 訓(xùn)練集個(gè)數(shù):{} 測(cè)試集數(shù)據(jù):{}'.format(path, len(train_files), len(test_files)))
這里的輸出結(jié)果:
現(xiàn)在可以看一下裁剪后的結(jié)果
df = pd.DataFrame()
for img,label in train_data: # 遍歷每個(gè)類別
# img = cv2.imread(fruit)
df = df.append({'類別':label, '文件名':file, '圖像寬':img.shape[1], '圖像高':img.shape[0]}, ignore_index=True)
df
?結(jié)果如下,我們可以看到大小已經(jīng)變成64x64了,當(dāng)然這是沒(méi)有打亂順序的,類別是從0開(kāi)始到4:
接下來(lái)就是打亂順序,這也是為了防止過(guò)擬合化
# 打亂訓(xùn)練集和測(cè)試集的順序
random.shuffle(train_data)
random.shuffle(test_data)
?再次輸出
df = pd.DataFrame()
for img,label in train_data: # 遍歷每個(gè)類別
# img = cv2.imread(fruit)
df = df.append({'類別':label, '文件名':file, '圖像寬':img.shape[1], '圖像高':img.shape[0]}, ignore_index=True)
df
?這一次的結(jié)果如下,類別順序已經(jīng)被打亂:
下面是保存訓(xùn)練集和測(cè)試集的數(shù)據(jù)集和標(biāo)簽
# 將訓(xùn)練集和測(cè)試集的圖片和標(biāo)簽分別存儲(chǔ)在numpy數(shù)組中
train_imgs = np.array([data[0] for data in train_data])
train_labels = np.array([data[1] for data in train_data])
test_imgs = np.array([data[0] for data in test_data])
test_labels = np.array([data[1] for data in test_data])
# 保存訓(xùn)練集和測(cè)試集
np.save('./datas/npy/32px/train_imgs_64.npy', train_imgs)
np.save('./datas/npy/32px/train_labels_64.npy', train_labels)
np.save('./datas/npy/32px/test_imgs_64.npy', test_imgs)
np.save('./datas/npy/32px/test_labels_64.npy', test_labels)
上面的數(shù)據(jù)集已經(jīng)做好了,那么接下來(lái)就到模型的訓(xùn)練了,模型的訓(xùn)練我就不一一解釋了,大家自己看代碼,我使用的是anaconda中的jupyter工具寫代碼文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-446377.html
#導(dǎo)庫(kù)
import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt
import urllib
import cv2
# 加載上面制作的數(shù)據(jù)集
train_imgs = np.load('./datas/npy/64px/train_imgs_64.npy')
train_labels = np.load('./datas/npy/64px/train_labels_64.npy')
test_imgs = np.load('./datas/npy/64px/test_imgs_64.npy')
test_labels = np.load('./datas/npy/64px/test_labels_64.npy')
#可以看看輸出緯度
train_imgs.shape
#模型構(gòu)建,這里我就構(gòu)建一個(gè)簡(jiǎn)單模型
def creatAlexNet():
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(64, kernel_size=(3, 3), strides=(1, 1), activation='relu', input_shape=(64, 64, 3)),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1)),
tf.keras.layers.Conv2D(128, kernel_size=(3, 3), strides=(1, 1), activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(1, 1)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(5, activation='softmax')
])
return model
#加載模型
model = creatAlexNet()
#顯示摘要
model.summary()
# 定義超參數(shù)
learning_rate = 0.001 #study
batch_size = 100 #單次訓(xùn)練樣本數(shù)(批次大小)
epochs = 20 #訓(xùn)練輪數(shù)
# 定義訓(xùn)練模式
model.compile(optimizer ='adam',#優(yōu)化器
loss='sparse_categorical_crossentropy',#損失函數(shù)
metrics=['accuracy'])#評(píng)估模型的方式
# 加載數(shù)據(jù)集并訓(xùn)練模型
history = model.fit(train_imgs, train_labels, batch_size=batch_size, epochs=epochs,
validation_split = 0.2)
# 評(píng)估模型
test_loss, test_acc = model.evaluate(test_imgs, test_labels, verbose=2)
print('Test accuracy:', test_acc)
#模型測(cè)試
preds = model.predict(test_imgs)
np.argmax(preds[20])
# 可視化測(cè)試
# 定義顯示圖像數(shù)據(jù)及其對(duì)應(yīng)標(biāo)簽的函數(shù)
# 圖像列表
label_dict={0:"wuweizi",1:"fengye",2:"guihua",3:"zhuye",4:"yinxing"}
def plot_images_labels_prediction(images,# 標(biāo)簽列表
labels,
preds,#預(yù)測(cè)值列表
index,#從第index個(gè)開(kāi)始顯示
num = 5): # 缺省一次顯示5幅
fig=plt.gcf()#獲取當(dāng)前圖表,Get Current Figure
fig.set_size_inches(12,6)#1英寸等于2.54cm
if num > 10:#最多顯示10個(gè)子圖
num = 10
for i in range(0, num):
ax = plt.subplot(2,5,i+1)#獲取當(dāng)前要處理的子圖
plt.tight_layout()
ax.imshow(images[index])
title=str(i)+','+label_dict[labels[index]]#構(gòu)建該圖上要顯示的title信息
if len(preds)>0:
title +='=>' + label_dict[np.argmax(preds[index])]
ax.set_title(title,fontsize=10)#顯示圖上的title信息
index += 1
plt.show()
plot_images_labels_prediction(test_imgs,test_labels, preds,10,30)
# 然后保存模型
model_filename ='models/plant_model.h5'
model.save(model_filename)
# 這里是從本地加載圖片對(duì)模型進(jìn)行測(cè)試
from PIL import Image
import numpy as np
loaded_model = tf.keras.models.load_model('models/plant_model.h5')
label_dict={0:"wuweizi",1:"fengye",2:"guihua",3:"zhuye",4:"yinxing"}
img = Image.open('./fengye.jpeg')
img = img.resize((64, 64))
img_arr = np.array(img) / 255.0
img_arr = img_arr.reshape(1, 64, 64, 3)
pred = model.predict(img_arr)
class_idx = np.argmax(pred)
plt.title("type:{}, pre_label:{}".format(label_dict[class_idx],class_idx))
plt.imshow(img, cmap=plt.get_cmap('gray'))
# 加載模型
loaded_model = tf.keras.models.load_model('models/plant_model.h5')
# 使用模型預(yù)測(cè)瀏覽器上的一張圖片
label_dict={0:"wuweizi",1:"fengye",2:"guihua",3:"zhuye",4:"yinxing"}
# 這里是從瀏覽器的網(wǎng)址中加載圖片進(jìn)行識(shí)別
url = 'https://newbbs-fd.zol-img.com.cn/t_s1200x5000/g5/M00/05/08/ChMkJ1wFsOGIcMt4AAGFQDPiUhEAAtkTQCj_EoAAYVY306.jpg'
with urllib.request.urlopen(url) as url_response:
img_array = np.asarray(bytearray(url_response.read()), dtype=np.uint8)
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
img_array = cv2.resize(img, (64, 64))
img_array = img_array / 255.0
img_array = np.expand_dims(img_array, axis=0)
predict_label = np.argmax(loaded_model.predict(img_array), axis=-1)[0]
plt.imshow(img, cmap=plt.get_cmap('gray'))
plt.title("Predict: {},Predict_label: {}".format(label_dict[predict_label],predict_label))
plt.xticks([])
plt.yticks([])
本次文章就到這里,感謝大家的支持!文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-446377.html
到了這里,關(guān)于ubuntu深度學(xué)習(xí)使用TensorFlow卷積神經(jīng)網(wǎng)絡(luò)——圖片數(shù)據(jù)集的制作以及制作好的數(shù)據(jù)集的使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!