python本機端使用訓練好Keras模型的實作。ai機器學習辨識的程式實作要有兩個前提,一是硬體軟體,二是訓練好的模型。
[ML python套件tensorflow-gpu keras軟體安裝說明]https://youtu.be/gEsLLIIAuGs
[谷哥Teachable Machine訓練Keras模型操作人、貓、狗辨識]https://youtu.be/HbZ5hggMbio
Code請開:
套件匯入,觀看cuda相關部份
- print('Teachable Machine之訓練好的keras model實作python code辨識部份')
- !nvidia-smi
- from keras.models import load_model # TensorFlow is required for Keras to work
- import cv2
- import numpy as np
- import tensorflow as tf
- print(tf.__version__)
- import keras
- print(keras.__version__)
- print(tf.test.is_built_with_cuda)
- tf.config.list_physical_devices('GPU')
- print('下面上傳converted_keras.zip &欲辨識圖檔要在圖片中央')
匯入model, labels
- #google colab加上files.upload
- #要unzip converted_keras.zip
- # Disable scientific notation for clarity
- np.set_printoptions(suppress=True)
- # Load the model
- model = load_model("keras_model.h5", compile=False)
- # Load the labels
- class_names = open("labels.txt", "r").readlines()
測試0.jpg~5.jpg圖裁切、縮放、正則化、預測
- ims=[str(i)+'.jpg' for i in range(6)]
- for fn in ims:
- image = cv2.imread(fn)
- h, w, c=image.shape
- s=min(h,w)
- print(h, ',', w, ',s=',s)
- #圖片裁切成正方形切
- if w<=h:
- image=image[(h-w)//2:w+(h-w)//2, :, :]
- else:
- image=image[:, (w-h)//2:h+(w-h)//2, :]
- print(image.shape)
- # Resize the raw image into (224-height,224-width) pixels
- image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
- #這部份在google colab要修改
- cv2.imshow('image',image)
- cv2.setWindowTitle('image', fn)
- cv2.waitKey(0)
- # Make the image a numpy array and reshape it to the models input shape.
- image = np.asarray(image, dtype=np.float32).reshape(1, 224, 224, 3)
- # Normalize the image array
- image = (image / 127.5) - 1
- # Predicts the model
- prediction = model.predict(image)
- index = np.argmax(prediction)
- class_name = class_names[index]
- confidence_score = prediction[0][index]
- print(prediction)
- # Print prediction and confidence score
- print("Class:", class_name[2:], end="")
- print("Confidence Score:", confidence_score * 100, "%")
- print('\n=================')
沒有留言:
張貼留言