Advertisement
Guest User

inference_raspi_5

a guest
Nov 24th, 2024
43
0
148 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.86 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. Raspberry Pi Live Image Inference
  4.  
  5. Continuously captures image from Raspberry Pi Camera module and perform
  6. inference using provided .eim model file. Outputs probabilities in console.
  7.  
  8. Author: EdgeImpulse, Inc.
  9. Date: June 8, 2021
  10. Updated: August 9, 2023
  11. License: Apache-2.0 (apache.org/licenses/LICENSE-2.0)
  12. """
  13.  
  14. import os, sys, time
  15. import cv2
  16. import numpy as np
  17. from picamera2 import Picamera2
  18. from edge_impulse_linux.runner import ImpulseRunner
  19.  
  20. # Settings
  21. model_file = "modelfile.eim"            # Trained ML model from Edge Impulse
  22. draw_fps = True                         # Draw FPS on screen
  23. res_width = 720                          # Resolution of camera (width)
  24. res_height = 720                         # Resolution of camera (height)
  25. rotation = 0                            # Camera rotation (0, 90, 180, or 270)
  26. cam_format = "RGB888"                   # Color format
  27. img_width = 96                          # Resize width to this for inference
  28. img_height = 96                         # Resize height to this for inference
  29.  
  30. # The ImpulseRunner module will attempt to load files relative to its location,
  31. # so we make it load files relative to this program instead
  32. dir_path = os.path.dirname(os.path.realpath(__file__))
  33. model_path = os.path.join(dir_path, model_file)
  34.  
  35. # Load the model file
  36. runner = ImpulseRunner(model_path)
  37.  
  38. # Initialize model
  39. try:
  40.  
  41.     # Print model information
  42.     model_info = runner.init()
  43.     print("Model name:", model_info['project']['name'])
  44.     print("Model owner:", model_info['project']['owner'])
  45.    
  46. # Exit if we cannot initialize the model
  47. except Exception as e:
  48.     print("ERROR: Could not initialize model")
  49.     print("Exception:", e)
  50.     if (runner):
  51.             runner.stop()
  52.     sys.exit(1)
  53.    
  54. # Initial framerate value
  55. fps = 0
  56.  
  57. # Interface with camera
  58. with Picamera2() as camera:
  59.  
  60.    
  61.     # Configure camera settings
  62.     config = camera.create_video_configuration(
  63.         main={"size": (res_width, res_height), "format": cam_format})
  64.     camera.configure(config)
  65.  
  66.     # Start camera
  67.     camera.start()
  68.    
  69.     # Continuously capture frames
  70.     while True:
  71.                                            
  72.         # Get timestamp for calculating actual framerate
  73.         timestamp = cv2.getTickCount()
  74.        
  75.         # Get array that represents the image
  76.         img = camera.capture_array()
  77.  
  78.         # Rotate image
  79.         if rotation == 0:
  80.             pass
  81.         elif rotation == 90:
  82.             img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
  83.         elif rotation == 180:
  84.             img = cv2.rotate(img, cv2.ROTATE_180)
  85.         elif rotation == 270:
  86.             img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
  87.         else:
  88.             print("ERROR: rotation not supported. Must be 0, 90, 180, or 270.")
  89.             break
  90.  
  91.         # Convert image to grayscale
  92.         img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
  93.        
  94.         # Resize captured image
  95.         img_resize = cv2.resize(img, (img_width, img_height))
  96.        
  97.         # Convert image to 1D vector of floating point numbers
  98.         features = np.reshape(img_resize, (img_width * img_height)) / 255
  99.        
  100.         # Edge Impulse model expects features in list format
  101.         features = features.tolist()
  102.        
  103.         # Perform inference
  104.         res = None
  105.         try:
  106.             res = runner.classify(features)
  107.         except Exception as e:
  108.             print("ERROR: Could not perform inference")
  109.             print("Exception:", e)
  110.            
  111.         # Display predictions and timing data
  112.         print("Output:", res)
  113.        
  114.         # Display prediction on preview
  115.         if res is not None:
  116.             # Find label with the highest probability
  117.             max_label = ""
  118.             max_val = 0
  119.             inferenceSpeed = res['timing']['classification']
  120.             print("inferenceSpeed", inferenceSpeed)
  121.             if "bounding_boxes" in res["result"]:
  122.                 for bb in res["result"]["bounding_boxes"]:
  123.                     if bb['value'] > 0:
  124.                         countObjects += 1
  125.                         max_val = bb['value']
  126.                         max_label = bb['label']
  127.                         bounding_boxes.append({
  128.                             'label': bb['label'],
  129.                             'x': int(bb['x']),
  130.                             'y': int(bb['y']),
  131.                             'width': int(bb['width']),
  132.                             'height': int(bb['height']),
  133.                             'confidence': bb['value']
  134.                         })
  135.                    
  136.             # Draw predicted label on bottom of preview
  137.             cv2.putText(img,
  138.                         max_label,
  139.                         (0, res_height - 20),
  140.                         cv2.FONT_HERSHEY_PLAIN,
  141.                         1,
  142.                         (255, 255, 255))
  143.                        
  144.             # Draw predicted class's confidence score (probability)
  145.             cv2.putText(img,
  146.                         str(round(max_val, 2)),
  147.                         (0, res_height - 2),
  148.                         cv2.FONT_HERSHEY_PLAIN,
  149.                         1,
  150.                         (255, 255, 255))
  151.        
  152.         # Draw framerate on frame
  153.         if draw_fps:
  154.             cv2.putText(img,
  155.                         "FPS: " + str(round(fps, 2)),
  156.                         (0, 12),
  157.                         cv2.FONT_HERSHEY_PLAIN,
  158.                         1,
  159.                         (255, 255, 255))
  160.        
  161.         # Show the frame
  162.         cv2.imshow("Frame", img)
  163.        
  164.         # Calculate framrate
  165.         frame_time = (cv2.getTickCount() - timestamp) / cv2.getTickFrequency()
  166.         fps = 1 / frame_time
  167.        
  168.         # Press 'q' to quit
  169.         if cv2.waitKey(1) == ord('q'):
  170.             break
  171.            
  172. # Clean up
  173. cv2.destroyAllWindows()
  174.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement