如何在 raspberry-pi 上 运行 tf.lite 建模而不是保存的 keras 模型
How to run tf.lite model on raspery-pi instead of saved keras model
我正在尝试使用 raspery-pi 对流量进行分类,为此我训练并保存了一个 .h5 文件的 keras 模型,但它消耗太多 cpu 所以我将其转换为 .tflite模型并尝试 运行。但是它给出了错误 OSError: SavedModel file does not exist at: yourmodel.tflite/{saved_model.pbtxt|saved_model.pb}
我检查了路径,这是我的代码。
另外我刚刚更改了那行: model = tensorflow.keras.models.load_model("my_model.h5")
到 model = tensorflow.keras.models.load_model("yourmodel.tflite")
import numpy as np
import cv2
import tensorflow
from tensorflow import keras
from tensorflow.keras.preprocessing import image
#############################################
frameWidth= 600 # CAMERA RESOLUTION
frameHeight = 480
brightness = 180
threshold = 0.75 # PROBABLITY THRESHOLD
font = cv2.FONT_HERSHEY_SIMPLEX
##############################################
# SETUP THE VIDEO CAMERA
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10, brightness)
cap.set(cv2.CAP_PROP_FPS, 3)
# IMPORT THE TRANNIED MODEL
model = tensorflow.keras.models.load_model("yourmodel.tflite")
#model = load_model('best_model.h5')
def equalize(img):
img = cv2.equalizeHist(img)
return img
def grayscale(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img
def preprocessing(img):
img = grayscale(img)
img = equalize(img)
img = img/255
return img
def getCalssName(classNo):
if classNo == 0: return 'Speed Limit 20 km/h'
elif classNo == 9: return 'No passing'
elif classNo == 12: return 'Priority road'
elif classNo == 13: return 'Yield'
elif classNo == 14: return 'Stop'
elif classNo == 38: return 'Keep right'
elif classNo == 39: return 'Keep left'
while True:
success, imgOrignal = cap.read()
img = np.asarray(imgOrignal)
#img = cv2.resize(img, (32, 32))
img = preprocessing(img)
cv2.imshow("Processed Image", img)
img = img.reshape(1, 32, 32, 1)
cv2.putText(imgOrignal, "CLASS: " , (20, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
cv2.putText(imgOrignal, "PROBABILITY: ", (20, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
# PREDICT IMAGE
predictions = model.predict(img)
classIndex = model.predict_classes(img)
probabilityValue =np.amax(predictions)
if probabilityValue > threshold:
print(getCalssName(classIndex))
#cv2.rectangle(image, coordinate[0],coordinate[1], (0, 255, 0), 1)
cv2.putText(imgOrignal,str(classIndex)+" "+str(getCalssName(classIndex)), (120, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
cv2.putText(imgOrignal, str(round(probabilityValue*100,2) )+"%", (180, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imshow("Result", imgOrignal)
if cv2.waitKey(1) and 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
尝试使用此代码保存您的 keras 模型
# model is your keras model
tflite_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
要加载和使用它,您需要 tf.lite.Interpreter
# instead of `model = tensorflow.keras.models.load_model("yourmodel.tflite")`
# use this code to load tflite model
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# replace `predictions = model.predict(img)` with this code
interpreter.set_tensor(input_details[0]['index'], img)
interpreter.invoke()
predictions = interpreter.get_tensor(output_details[0]['index'])
我正在尝试使用 raspery-pi 对流量进行分类,为此我训练并保存了一个 .h5 文件的 keras 模型,但它消耗太多 cpu 所以我将其转换为 .tflite模型并尝试 运行。但是它给出了错误 OSError: SavedModel file does not exist at: yourmodel.tflite/{saved_model.pbtxt|saved_model.pb}
我检查了路径,这是我的代码。
另外我刚刚更改了那行: model = tensorflow.keras.models.load_model("my_model.h5")
到 model = tensorflow.keras.models.load_model("yourmodel.tflite")
import numpy as np
import cv2
import tensorflow
from tensorflow import keras
from tensorflow.keras.preprocessing import image
#############################################
frameWidth= 600 # CAMERA RESOLUTION
frameHeight = 480
brightness = 180
threshold = 0.75 # PROBABLITY THRESHOLD
font = cv2.FONT_HERSHEY_SIMPLEX
##############################################
# SETUP THE VIDEO CAMERA
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10, brightness)
cap.set(cv2.CAP_PROP_FPS, 3)
# IMPORT THE TRANNIED MODEL
model = tensorflow.keras.models.load_model("yourmodel.tflite")
#model = load_model('best_model.h5')
def equalize(img):
img = cv2.equalizeHist(img)
return img
def grayscale(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img
def preprocessing(img):
img = grayscale(img)
img = equalize(img)
img = img/255
return img
def getCalssName(classNo):
if classNo == 0: return 'Speed Limit 20 km/h'
elif classNo == 9: return 'No passing'
elif classNo == 12: return 'Priority road'
elif classNo == 13: return 'Yield'
elif classNo == 14: return 'Stop'
elif classNo == 38: return 'Keep right'
elif classNo == 39: return 'Keep left'
while True:
success, imgOrignal = cap.read()
img = np.asarray(imgOrignal)
#img = cv2.resize(img, (32, 32))
img = preprocessing(img)
cv2.imshow("Processed Image", img)
img = img.reshape(1, 32, 32, 1)
cv2.putText(imgOrignal, "CLASS: " , (20, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
cv2.putText(imgOrignal, "PROBABILITY: ", (20, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
# PREDICT IMAGE
predictions = model.predict(img)
classIndex = model.predict_classes(img)
probabilityValue =np.amax(predictions)
if probabilityValue > threshold:
print(getCalssName(classIndex))
#cv2.rectangle(image, coordinate[0],coordinate[1], (0, 255, 0), 1)
cv2.putText(imgOrignal,str(classIndex)+" "+str(getCalssName(classIndex)), (120, 35), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
cv2.putText(imgOrignal, str(round(probabilityValue*100,2) )+"%", (180, 75), font, 0.75, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imshow("Result", imgOrignal)
if cv2.waitKey(1) and 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
尝试使用此代码保存您的 keras 模型
# model is your keras model
tflite_model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
要加载和使用它,您需要 tf.lite.Interpreter
# instead of `model = tensorflow.keras.models.load_model("yourmodel.tflite")`
# use this code to load tflite model
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# replace `predictions = model.predict(img)` with this code
interpreter.set_tensor(input_details[0]['index'], img)
interpreter.invoke()
predictions = interpreter.get_tensor(output_details[0]['index'])