keras 匯入本地圖片測試集並預測結果
阿新 • • 發佈:2021-01-03
技術標籤:影象識別tensorflow
需要的庫
from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
import numpy as np
import os
import cv2
from PIL import Image
model = tf.keras.models.load_model('sand_model2') #載入已有模型
方法1 (圖片較多,按照字典形式存放)
ImageDataGenerator方法
data_dir='C:/Users/HP/Desktop/tf_data/sand_train' #輸入自己的目錄,此目錄下應有多個子資料夾
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
data_dir,
shuffle=False,#測試集不需要打亂
target_size=(256,256), #圖片大小,預設256,256
batch_size=5, #可任意設定
class_mode='categorical')
#用生成器方式預測
predictions= model.predict_generator(test_generator)
#顯示結果
result=[]
for iii in range(predictions.shape[0]):
result.append(np.argmax(predictions[iii]))
print('result',result)
方法2(圖片較少,按照字典形式存放)
直接讀入,使用Image.open
data_dir = 'C:/Users/HP/Desktop/tf_data/sand_train2'
def read_data(data_dir):
datas = [] #儲存圖片資料
labelnames= [] #儲存標籤名(資料夾名)
labels = [] #儲存標籤
fpaths = [] #儲存每個圖片路徑
co=0 #標籤,按資料夾順序分別設為0,1,2......
for fname in os.listdir(data_dir):#遍歷每個資料夾
fpath = data_dir+'/'+fname
labelnames.append(str(fname))#資料夾名即為標籤名
for ffname in os.listdir(fpath):#遍歷一個資料夾下每張圖片
try:
image = Image.open(os.path.join(fpath, ffname))
im = np.array(image)
if len(im.shape)==2:
image=Image.merge('RGB', (image, image, image))#如果是灰度圖,擴充套件為三通道
data = np.array(image) / 255.0
data.astype('float32')
datas.append(data)
label = co
labels.append(label)
everypath = fpath + '/' + ffname
fpaths.append(everypath)#記下每張圖的路徑
except:
continue
co=co+1 #標籤+1
datas = np.array(datas)
labels = np.array(labels)
print("shape of datas: {}\tkind of labels: {}".format(datas.shape,labels.shape))
return fpaths, datas, labels,labelnames
#讀取
fpaths, test_images, test_labels,labelnames = read_data(data_dir)
#預測
predictions = model.predict(test_images)
#顯示結果
result=[]
for iii in range(predictions.shape[0]):
result.append(np.argmax(predictions[iii]))
print('result',result)
方法3(圖片較少,沒有標籤,存在一個資料夾裡)
使用cv2.imread
#直接讀取圖片
def get_image(data_dir, img_cols, img_rows, color_type=3,normalize=True):
imgs = []
for fname in os.listdir(data_dir):
try:
if color_type == 1:
img = cv2.imread(os.path.join(data_dir, fname), 0)
elif color_type == 3:
img = cv2.imread(os.path.join(data_dir, fname))
# Reduce size
resized = cv2.resize(img, (img_cols, img_rows))
if normalize:
resized = resized.astype('float32')
resized /= 255
imgs.append(resized)
except:
continue
imgs=np.array(imgs)
print("shape of datas: {}".format(imgs.shape))
return imgs
#讀取10張測試圖片
imatest =get_image('C:/Users/HP/Desktop/tf_data/test/test',256,256)
#預測
predictions = model.predict(imatest)
#顯示結果
result=[]
for iii in range(predictions.shape[0]):
result.append(np.argmax(predictions[iii]))
print('result',result)
方法4(已有所有圖片路徑和標籤)
此處data_dir 為一個列表,存放所有圖片路徑
def get_image_from_paths(data_dir, img_cols, img_rows, color_type=3, normalize=True):
imgs = []
for fname in data_dir:
try:
if color_type == 1:
img = cv2.imread(fname, 0)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
elif color_type == 3:
img = cv2.imread(fname)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Reduce size
resized = cv2.resize(img, (img_cols, img_rows))
if normalize:
resized = resized.astype('float32')
resized /= 255
imgs.append(resized)
except:
continue
imgs = np.array(imgs)
print("shape of datas: {}".format(imgs.shape))
return imgs
imatest =get_image_from_paths(your_paths,256,256) #讀取
#後續與上一方法相同
輸出形式
#結果
result [0, 0, 0, 0, 2, 0, 0, 0, 0, 0]