|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Created on Sat Jul 24 12:43:27 2021 |
| 4 | +
|
| 5 | +@author: user |
| 6 | +""" |
| 7 | + |
| 8 | +""" |
| 9 | +File name: 演算法對接範例程式_v01.py |
| 10 | +Date: 2021/07/19 |
| 11 | +Version: v01 |
| 12 | +Usage: 演算法對接主程式 |
| 13 | +""" |
| 14 | + |
| 15 | + |
| 16 | +#region import package |
| 17 | + |
| 18 | +import os |
| 19 | +import numpy as np |
| 20 | + |
| 21 | +# def load_image_files |
| 22 | +import cv2 |
| 23 | +import glob |
| 24 | + |
| 25 | +# def loadModel |
| 26 | +from tensorflow.keras.models import load_model |
| 27 | + |
| 28 | +# predict |
| 29 | +from tensorflow.keras.models import Model |
| 30 | + |
| 31 | +#endregion |
| 32 | + |
| 33 | +import tensorflow as tf |
| 34 | +if tf.test.is_gpu_available(): |
| 35 | + print('有啟用GPU') |
| 36 | +else: |
| 37 | + print('尚未啟用GPU') |
| 38 | + |
| 39 | +class AI_Algo(): |
| 40 | + """ |
| 41 | + A class used to ... |
| 42 | +
|
| 43 | + ... |
| 44 | +
|
| 45 | + Attributes |
| 46 | + ---------- |
| 47 | + data : ndarray (n, w, h, 3) |
| 48 | + the input image of training model |
| 49 | + targets : ndarray (n, label) |
| 50 | + the target label of training model |
| 51 | + model : |
| 52 | + Trained model |
| 53 | +
|
| 54 | + Methods |
| 55 | + ------- |
| 56 | + __init__(...) |
| 57 | + Class initialization |
| 58 | + fit(X, y) |
| 59 | + Train model |
| 60 | + saveModel(path): |
| 61 | + Save model |
| 62 | + loadModel(path): |
| 63 | + Load model |
| 64 | + predict(X): |
| 65 | + Predict model |
| 66 | + """ |
| 67 | + |
| 68 | + classLabel= { |
| 69 | + "0":{"name":"CarOnly","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 70 | + "1":{"name":"DirectForMotor","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 71 | + "2":{"name":"KeepLeft","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 72 | + "3":{"name":"KeepRight","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 73 | + "4":{"name":"LeftTurn","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 74 | + "5":{"name":"RightTurn","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 75 | + "6":{"name":"Roundabout","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 76 | + "7":{"name":"StraightOnly","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 77 | + "8":{"name":"StraightOrLeft","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 78 | + "9":{"name":"StraightOrRight","info":"FollowSign","color":"blue", 'Group': 'M'}, |
| 79 | + "10":{"name":"Other_SignC","info":"Look UP","color":"green", 'Group': 'P'}, |
| 80 | + "11":{"name":"Other_SignD","info":"Look UP","color":"green", 'Group': 'W'}, |
| 81 | + "12":{"name":"Other_SignT","info":"Look UP","color":"green", 'Group': 'W'}, |
| 82 | + "13":{"name":"Other_SignT2","info":"Look UP","color":"green", 'Group': 'W'}, |
| 83 | + "14":{"name":"NoEntry","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 84 | + "15":{"name":"NoLeftTurn","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 85 | + "16":{"name":"NoRandLTurn","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 86 | + "17":{"name":"NoRightTurn","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 87 | + "18":{"name":"NoStopping","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 88 | + "19":{"name":"NoUTurn","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 89 | + "20":{"name":"ALTRightTurn","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 90 | + "21":{"name":"SpdLimit100","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 91 | + "22":{"name":"SpdLimit120","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 92 | + "23":{"name":"SpdLimit20","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 93 | + "24":{"name":"SpdLimit30","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 94 | + "25":{"name":"SpdLimit40","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 95 | + "26":{"name":"SpdLimit50","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 96 | + "27":{"name":"SpdLimit60","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 97 | + "28":{"name":"Spdimit70","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 98 | + "29":{"name":"Spdimit80","info":"Be Aware","color":"red", 'Group': 'P'}, |
| 99 | + "30":{"name":"Children","info":"Caution","color":"orange", 'Group': 'W'}, |
| 100 | + "31":{"name":"CurveToLeft","info":"Caution","color":"orange", 'Group': 'W'}, |
| 101 | + "32":{"name":"CurveToRight","info":"Caution","color":"orange", 'Group': 'W'}, |
| 102 | + "33":{"name":"DoubleCurve1","info":"Caution","color":"orange", 'Group': 'W'}, |
| 103 | + "34":{"name":"DoubleCurve2","info":"Caution","color":"orange", 'Group': 'W'}, |
| 104 | + "35":{"name":"FallingRocks","info":"Caution","color":"orange", 'Group': 'W'}, |
| 105 | + "36":{"name":"OtherDanger","info":"Caution","color":"orange", 'Group': 'W'}, |
| 106 | + "37":{"name":"Pedestrians","info":"Caution","color":"orange", 'Group': 'W'}, |
| 107 | + "38":{"name":"RoadNarrows","info":"Caution","color":"orange", 'Group': 'W'}, |
| 108 | + "39":{"name":"RoadLights","info":"Caution","color":"orange", 'Group': 'W'}, |
| 109 | + "40":{"name":"SeparateIsland","info":"Caution","color":"orange", 'Group': 'W'}, |
| 110 | + "41":{"name":"SlipperyRoad","info":"Caution","color":"orange", 'Group': 'W'}, |
| 111 | + "42":{"name":"Slow","info":"Caution","color":"orange", 'Group': 'W'}, |
| 112 | + "43":{"name":"Stop","info":"Caution","color":"orange", 'Group': 'W'}, |
| 113 | + "44":{"name":"UnevenRoad","info":"Caution","color":"orange", 'Group': 'W'}, |
| 114 | + } |
| 115 | + |
| 116 | + DictImage_stan_Sign = {} |
| 117 | + Dict_name_2_Group = {} |
| 118 | + |
| 119 | + def __init__(self): # 參數 |
| 120 | + """ |
| 121 | + Constructor: Class initialization |
| 122 | + """ |
| 123 | + print('__init__') |
| 124 | + self.initial_DictImage_stan_Sign() |
| 125 | + self.initial_Dict_name_2_Group() |
| 126 | + return |
| 127 | + |
| 128 | + def initial_DictImage_stan_Sign(self): |
| 129 | + dir_image = 'GUI Image/Sign/Standard_Sample/' |
| 130 | + for i in range(len(self.classLabel)): |
| 131 | + path = dir_image + self.classLabel[str(i)]['Group'] + '/' + self.classLabel[str(i)]['name'] + '.jpg' |
| 132 | + self.DictImage_stan_Sign[self.classLabel[str(i)]['name']] = cv2.imdecode(np.fromfile(path, dtype=np.uint8), 1) |
| 133 | + return |
| 134 | + |
| 135 | + def initial_Dict_name_2_Group(self): |
| 136 | + for i in range(len(self.classLabel)): |
| 137 | + self.Dict_name_2_Group[self.classLabel[str(i)]['name']] = self.classLabel[str(i)]['Group'] |
| 138 | + return |
| 139 | + |
| 140 | + def loadModel(self, path): |
| 141 | + """ |
| 142 | + Load model |
| 143 | + ''' |
| 144 | + Parameters |
| 145 | + ---------- |
| 146 | + path : string |
| 147 | + Loading model path |
| 148 | + """ |
| 149 | + with tf.device('/cpu:0'): |
| 150 | + self.model = load_model(path) |
| 151 | + return |
| 152 | + |
| 153 | + def predict(self, X_test): |
| 154 | + with tf.device('/cpu:0'): |
| 155 | + y_pred = self.model.predict(X_test) |
| 156 | + # 整理y_pred的格式 |
| 157 | + for i in range(len(y_pred)): |
| 158 | + temp_list = [] |
| 159 | + |
| 160 | + temp_list.append(y_pred[i]) |
| 161 | + arr_total = np.sum(temp_list) |
| 162 | + y_pred[i] = y_pred[i]/arr_total |
| 163 | + |
| 164 | + # 得到y_pred的機率 |
| 165 | + y_pred_probability = [] |
| 166 | + for i in range(len(y_pred)): |
| 167 | + |
| 168 | + probability = y_pred[i].max() |
| 169 | + y_pred_probability.append(probability) |
| 170 | + |
| 171 | + # 得到y_pred的label |
| 172 | + predictresult = [] |
| 173 | + for i in range(X_test.shape[0]): |
| 174 | + predictresult.append(y_pred[i].argmax()) |
| 175 | + |
| 176 | + # 最終輸出格式: [('M_CarOnly', 0.35248378, 'M', "red")] |
| 177 | + output = [] |
| 178 | + for i in range(len(y_pred)): |
| 179 | + int_dict = str(predictresult[i]) |
| 180 | + name_dict = self.classLabel[int_dict]['name'] |
| 181 | + shorthand = self.classLabel[int_dict]['info'] |
| 182 | + color = self.classLabel[int_dict]['color'] |
| 183 | + |
| 184 | + output.append(tuple([name_dict, y_pred_probability[i], shorthand, color])) |
| 185 | + return output |
| 186 | + |
| 187 | + def predict2(self, listImg: list, dimension=(32, 32), BGR=False): # Jeff Revised! |
| 188 | + # Preprocess |
| 189 | + raw_data_test = [] |
| 190 | + for img in listImg: |
| 191 | + img = img[:, :, ::(-1 if BGR else 1)] |
| 192 | + resized = cv2.resize(img, dimension, interpolation = cv2.INTER_AREA) |
| 193 | + raw_data_test.append(resized) |
| 194 | + X_test = np.array(raw_data_test) |
| 195 | + |
| 196 | + with tf.device('/cpu:0'): |
| 197 | + y_pred = self.model.predict(X_test) |
| 198 | + # 整理y_pred的格式 |
| 199 | + for i in range(len(y_pred)): |
| 200 | + temp_list = [] |
| 201 | + |
| 202 | + temp_list.append(y_pred[i]) |
| 203 | + arr_total = np.sum(temp_list) |
| 204 | + y_pred[i] = y_pred[i]/arr_total |
| 205 | + |
| 206 | + # 得到y_pred的機率 |
| 207 | + y_pred_probability = [] |
| 208 | + for i in range(len(y_pred)): |
| 209 | + |
| 210 | + probability = y_pred[i].max() |
| 211 | + y_pred_probability.append(probability) |
| 212 | + |
| 213 | + # 得到y_pred的label |
| 214 | + predictresult = [] |
| 215 | + for i in range(X_test.shape[0]): |
| 216 | + predictresult.append(y_pred[i].argmax()) |
| 217 | + |
| 218 | + # 最終輸出格式: [('M_CarOnly', 0.35248378, 'M', "red")] |
| 219 | + output = [] |
| 220 | + for i in range(len(y_pred)): |
| 221 | + int_dict = str(predictresult[i]) |
| 222 | + name_dict = self.classLabel[int_dict]['name'] |
| 223 | + shorthand = self.classLabel[int_dict]['info'] |
| 224 | + color = self.classLabel[int_dict]['color'] |
| 225 | + |
| 226 | + output.append(tuple([name_dict, y_pred_probability[i], shorthand, color])) |
| 227 | + return output |
| 228 | + |
| 229 | + def load_image_files(self, container_path, dimension=(32, 32)): |
| 230 | + """ |
| 231 | + Load image files with categories as subfolder names |
| 232 | + which performs like scikit-learn sample dataset |
| 233 | + Parameters |
| 234 | + ---------- |
| 235 | + container_path : string or unicode |
| 236 | + Path to the main folder holding one subfolder per category |
| 237 | + dimension : tuple |
| 238 | + size to which image are adjusted to |
| 239 | + Returns |
| 240 | + ------- |
| 241 | + Bunch |
| 242 | + """ |
| 243 | + |
| 244 | + raw_data_test = [] |
| 245 | + test_len = [] |
| 246 | + size = dimension |
| 247 | + |
| 248 | + |
| 249 | + # link = container_path + "*.jpg" |
| 250 | + link = os.path.join(container_path, '*.jpg') |
| 251 | + path = glob.glob(link) |
| 252 | + |
| 253 | + pre_size = len(raw_data_test) |
| 254 | + #print(pre_size) |
| 255 | + |
| 256 | + |
| 257 | + for img in path: |
| 258 | + #n = cv2.imread(img) |
| 259 | + n = cv2.imdecode(np.fromfile(img, dtype=np.uint8), 1) # Jeff Revised! |
| 260 | + n = cv2.cvtColor(n, cv2.COLOR_BGR2RGB) |
| 261 | + resized = cv2.resize(n, size, interpolation = cv2.INTER_AREA) |
| 262 | + raw_data_test.append(resized) |
| 263 | + |
| 264 | + real_size = len(raw_data_test) - pre_size |
| 265 | + |
| 266 | + test_len.append(real_size) |
| 267 | + |
| 268 | + test_len = np.array(raw_data_test) |
| 269 | + |
| 270 | + return test_len |
| 271 | + |
| 272 | +if __name__ == "__main__": # 演算法測試 |
| 273 | + ai_Algo = AI_Algo() |
| 274 | + |
| 275 | + ai_Algo.loadModel(r"D:\Machine Learning\工研院產業新尖兵\專題\交通號誌辨識\Model\sign_batch.h5") |
| 276 | + |
| 277 | + #region Preprocess |
| 278 | + |
| 279 | + #讀取圖片需要Monica的奧援 |
| 280 | + data = ai_Algo.load_image_files(r"D:\Machine Learning\工研院產業新尖兵\專題\交通號誌辨識\UNclear") |
| 281 | + #endregion |
| 282 | + x = ai_Algo.predict(data) |
| 283 | + print(x) |
| 284 | + |
| 285 | + #region Train model |
| 286 | + |
| 287 | + #endregion |
| 288 | + |
| 289 | + #region Test model |
| 290 | + |
| 291 | + print('-' * 30) |
| 292 | + |
| 293 | + # import glob |
| 294 | + # listImg = [] |
| 295 | + # dir_img = 'D:/Machine Learning/工研院產業新尖兵/專題/Code/yolov5/yolov5/runs/detect/exp6/crops/sign/' |
| 296 | + # for path in glob.glob(dir_img + '*.jpg'): |
| 297 | + # print(path) |
| 298 | + # listImg.append(cv2.imdecode(np.fromfile(path, dtype=np.uint8), 1)) |
| 299 | + |
| 300 | + # print(ai_Algo.predict2(listImg, BGR=True)) |
| 301 | + |
| 302 | + #endregion |
0 commit comments