|
|
|
|
|
import tensorflow as tf |
|
|
import numpy as np |
|
|
from PIL import Image |
|
|
import json |
|
|
import os |
|
|
|
|
|
class MobilePhoneUsageDetector: |
|
|
def __init__(self, model_path): |
|
|
"""Initialize the model""" |
|
|
self.model = tf.keras.models.load_model(model_path) |
|
|
with open('model_config.json', 'r') as f: |
|
|
self.config = json.load(f) |
|
|
|
|
|
self.img_size = tuple(self.config['input_shape'][:2]) |
|
|
self.class_names = list(self.config['classes'].keys()) |
|
|
|
|
|
def preprocess_image(self, image): |
|
|
"""Preprocess image for model prediction""" |
|
|
if isinstance(image, str): |
|
|
image = Image.open(image).convert('RGB') |
|
|
elif isinstance(image, np.ndarray): |
|
|
image = Image.fromarray(image) |
|
|
|
|
|
|
|
|
image = image.resize(self.img_size) |
|
|
|
|
|
|
|
|
image_array = np.array(image) / 255.0 |
|
|
|
|
|
|
|
|
image_array = np.expand_dims(image_array, axis=0) |
|
|
|
|
|
return image_array |
|
|
|
|
|
def predict(self, image): |
|
|
"""Predict phone usage in image""" |
|
|
|
|
|
processed_image = self.preprocess_image(image) |
|
|
|
|
|
|
|
|
prediction = self.model.predict(processed_image)[0][0] |
|
|
|
|
|
|
|
|
predicted_class = self.class_names[1] if prediction > 0.5 else self.class_names[0] |
|
|
confidence = prediction if prediction > 0.5 else 1 - prediction |
|
|
|
|
|
return { |
|
|
'class': predicted_class, |
|
|
'confidence': float(confidence), |
|
|
'raw_prediction': float(prediction) |
|
|
} |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
detector = MobilePhoneUsageDetector('fine_tuned_phone_detection_model.h5') |
|
|
|
|
|
|
|
|
result = detector.predict('example_image.jpg') |
|
|
print(f"Prediction: {result}") |
|
|
|