import cv2
import numpy as np
import tensorflow as tf
model = tf.keras.applications.MobileNetV2(weights="imagenet")
def preprocess_image(image):
img = cv2.resize(image, (224, 224))
img = img.astype("float32")
img = tf.keras.applications.mobilenet_v2.preprocess_input(img)
img = np.expand_dims(img, axis=0)
return img
def is_human_detected(predictions):
for _, label, score in predictions[0]:
if label == "person" and score > 0.5:
return True
return False
def stop_car():
print("Human detected! Stopping the car.")
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
preprocessed_image = preprocess_image(frame)
predictions = model.predict(preprocessed_image)
decoded_predictions = tf.keras.applications.mobilenet_v2.decode_predictions(predictions, top=1)
if is_human_detected(decoded_predictions):
stop_car()
cv2.imshow('Headlight Camera', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the video capture and destroy all windows
cap.release()
cv2.destroyAllWindows()
Comments