Advertisement
NaroxEG

Keras Model - Py>Bluetooth

Jul 5th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. from keras.models import load_model # TensorFlow is required for Keras to work
  2. import cv2 # Install opencv-python
  3. import numpy as np
  4. import serial
  5. import time
  6.  
  7. bluetooth_port = 'COM3'
  8. baud_rate = 9600
  9.  
  10. ser = serial.Serial(bluetooth_port, baud_rate)
  11. time.sleep(2) # Wait for connection
  12.  
  13. # Disable scientific notation for clarity
  14. np.set_printoptions(suppress=True)
  15.  
  16. # Load the model
  17. model = load_model("keras_Model.h5", compile=False)
  18.  
  19. # Load the labels
  20. class_names = open("labels.txt", "r").readlines()
  21.  
  22. # CAMERA can be 0 or 1 based on default camera of your computer
  23. camera = cv2.VideoCapture(0)
  24.  
  25. while True:
  26. # Grab the webcamera's image.
  27. ret, image = camera.read()
  28.  
  29. # Resize the raw image into (224-height,224-width) pixels
  30. image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
  31.  
  32. # Show the image in a window
  33. cv2.imshow("Webcam Image", image)
  34.  
  35. # Make the image a numpy array and reshape it to the models input shape.
  36. image = np.asarray(image, dtype=np.float32).reshape(1, 224, 224, 3)
  37.  
  38. # Normalize the image array
  39. image = (image / 127.5) - 1
  40.  
  41. # Predicts the model
  42. prediction = model.predict(image)
  43. index = np.argmax(prediction)
  44. class_name = class_names[index]
  45. confidence_score = prediction[0][index]
  46.  
  47. # Print prediction and confidence score
  48. print("Class:", class_name[2:], end="")
  49. print("Confidence Score:", str(np.round(confidence_score * 100))[:-2], "%")
  50.  
  51. ser.write(class_name[2:].encode())
  52.  
  53. # Listen to the keyboard for presses.
  54. keyboard_input = cv2.waitKey(1)
  55.  
  56. # 27 is the ASCII for the esc key on your keyboard.
  57. if keyboard_input == 27:
  58. break
  59.  
  60. camera.release()
  61. cv2.destroyAllWindows()
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement