arthurhzna / PredictH5

0 stars 0 forks source link

tflite predict #1

Open arthurhzna opened 3 days ago

arthurhzna commented 3 days ago

import numpy as np import tensorflow as tf from tensorflow.keras.preprocessing.image import load_img, img_to_array

Load your TFLite model

interpreter = tf.lite.Interpreter(model_path='/path/to/your/mobilenet_mask2.tflite') # Update with your TFLite model path interpreter.allocate_tensors()

Get input and output details

input_details = interpreter.get_input_details() output_details = interpreter.get_output_details()

Function to predict if an image has glasses or not using TFLite

def predict_image(image_path):

Load and preprocess the image

image = load_img(image_path, target_size=(224, 224))  # Adjust size based on the model's requirement
image_array = img_to_array(image) / 255.0  # Rescale pixel values to [0, 1]
image_array = np.expand_dims(image_array, axis=0)  # Add batch dimension

# Set the tensor to the interpreter
interpreter.set_tensor(input_details[0]['index'], image_array.astype(np.float32))

# Run inference
interpreter.invoke()

# Get the prediction result
prediction = interpreter.get_tensor(output_details[0]['index'])

# Apply threshold for binary classification
predicted_class = (prediction > 0.5).astype("int32")  # Change threshold if necessary

return predicted_class

Provide the path to the image from your internal storage

image_path = '/path/to/your/image.jpg' # Update this with the path to your image file predicted_class = predict_image(image_path)

Display the prediction result

result = 'No MASK' if predicted_class[0][0] == 1 else 'MASK' print(f'Prediction: {result}')

arthurhzna commented 3 days ago

tflite.txt