Advertisement
xosski

Raspberry pi security camera

Dec 4th, 2024
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.64 KB | None | 0 0
  1. import os
  2. import subprocess
  3. import sys
  4. import time
  5. import cv2
  6. import numpy as np
  7. import tflite_runtime.interpreter as tflite
  8. from picamera2 import Picamera2, Preview
  9. from gpiozero import AngularServo
  10. import RPi.GPIO as GPIO
  11. import logging
  12.  
  13. # Configure logging
  14. logging.basicConfig(filename='/home/carlitos/Python/tLite/process.log', level=logging.INFO,
  15. format='%(asctime)s - %(levelname)s - %(message)s')
  16.  
  17. # GPIO setup for the ultrasonic sensor
  18. TRIG = 23
  19. ECHO = 24
  20. GPIO.setmode(GPIO.BCM)
  21. GPIO.setup(TRIG, GPIO.OUT)
  22. GPIO.setup(ECHO, GPIO.IN)
  23.  
  24. # Servo setup
  25. servo = AngularServo(27, min_pulse_width=0.0006, max_pulse_width=0.0023)
  26.  
  27. # File paths
  28. MODEL_PATH = "model.tflite"
  29. LABELS_PATH = "labels.txt"
  30. IMAGE_DIR = "/home/carlitos/Python/tLite/captured_images"
  31.  
  32. # Ensure the image directory exists
  33. os.makedirs(IMAGE_DIR, exist_ok=True)
  34.  
  35. # Load labels
  36. with open(LABELS_PATH, "r") as f:
  37. labels = f.read().splitlines()
  38.  
  39. # Initialize the camera
  40. picam2 = Picamera2()
  41. camera_config = picam2.create_preview_configuration({"size": (980, 540)})
  42. picam2.configure(camera_config)
  43. picam2.start_preview(Preview.QTGL)
  44. picam2.start()
  45.  
  46. # TensorFlow Lite model setup
  47. interpreter = tflite.Interpreter(model_path=MODEL_PATH)
  48. interpreter.allocate_tensors()
  49. input_details = interpreter.get_input_details()
  50. output_details = interpreter.get_output_details()
  51.  
  52.  
  53. def measure_distance():
  54. """Measure distance using the ultrasonic sensor."""
  55. GPIO.output(TRIG, False)
  56. time.sleep(0.1)
  57.  
  58. GPIO.output(TRIG, True)
  59. time.sleep(0.00001)
  60. GPIO.output(TRIG, False)
  61.  
  62. while GPIO.input(ECHO) == 0:
  63. pulse_start = time.time()
  64.  
  65. while GPIO.input(ECHO) == 1:
  66. pulse_end = time.time()
  67.  
  68. pulse_duration = pulse_end - pulse_start
  69. distance = pulse_duration * 17150
  70. distance = round(distance, 2)
  71. return distance
  72.  
  73.  
  74. def capture_image():
  75. """Capture an image from the camera."""
  76. image = picam2.capture_array()
  77. if image is None or image.size == 0:
  78. logging.error("Failed to capture image.")
  79. raise Exception("Failed to capture image.")
  80.  
  81. # Save the image with a timestamp
  82. timestamp = time.strftime("%Y%m%d-%H%M%S")
  83. image_path = os.path.join(IMAGE_DIR, f"captured_image_{timestamp}.jpg")
  84. cv2.imwrite(image_path, image)
  85. logging.info(f"Image captured and saved: {image_path}")
  86. return image_path
  87.  
  88.  
  89. def classify_image(image_path):
  90. """Classify the captured image using the TensorFlow Lite model."""
  91. try:
  92. image = cv2.imread(image_path)
  93. image = cv2.resize(image, (input_details[0]['shape'][2], input_details[0]['shape'][1]))
  94. image = np.array(image, dtype=np.uint8)
  95. image = np.expand_dims(image, axis=0)
  96.  
  97. interpreter.set_tensor(input_details[0]['index'], image)
  98. interpreter.invoke()
  99. output_data = interpreter.get_tensor(output_details[0]['index'])
  100.  
  101. predicted_label = labels[np.argmax(output_data)]
  102. confidence = (np.max(output_data) / 255) * 100
  103. logging.info(f"Image classified: {predicted_label} with confidence {confidence:.2f}")
  104. return predicted_label, confidence
  105. except Exception as e:
  106. logging.error(f"Error during classification: {e}")
  107. return "Unknown", 0.0
  108.  
  109.  
  110. def control_servo(label):
  111. """Control the servo based on the classified label."""
  112. if label == "1 Papel/Cartão":
  113. logging.info("Material detected: Papel/Cartão, moving servo to 90°")
  114. servo.angle = 90
  115. time.sleep(2)
  116. servo.angle = -90
  117. elif label == "Another Object":
  118. logging.info("Material detected: Another Object, moving servo to 45°")
  119. servo.angle = 45
  120. time.sleep(1)
  121. servo.angle = -45
  122. else:
  123. logging.info(f"Material detected: {label}, no servo action.")
  124.  
  125.  
  126. try:
  127. while True:
  128. distance = measure_distance()
  129. logging.info(f"Distance: {distance} cm")
  130.  
  131. if distance < 10: # Object detected within 10 cm
  132. logging.info("Object detected, capturing image...")
  133. image_path = capture_image()
  134.  
  135. logging.info("Classifying image...")
  136. label, confidence = classify_image(image_path)
  137.  
  138. logging.info(f"Material detected: {label} with confidence {confidence:.2f}")
  139. control_servo(label)
  140.  
  141. time.sleep(5) # Delay before next measurement
  142. else:
  143. time.sleep(1) # Check every second if no object is detected
  144.  
  145. except KeyboardInterrupt:
  146. logging.info("Program interrupted by user.")
  147. finally:
  148. picam2.stop()
  149. GPIO.cleanup()
  150. logging.info("GPIO cleanup completed.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement