qrcode123.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import cv2
  2. import pygame
  3. from pyzbar.pyzbar import decode
  4. # Initialize pygame for audio playback
  5. pygame.mixer.init()
  6. print("Pygame initialized.")
  7. # Function to play audio
  8. def play_audio(file_path):
  9. print(f"Attempting to play audio: {file_path}")
  10. pygame.mixer.music.load(file_path)
  11. pygame.mixer.music.play()
  12. while pygame.mixer.music.get_busy():
  13. continue
  14. print("Finished playing audio.")
  15. # Capture video from camera
  16. cap = cv2.VideoCapture(0)
  17. if not cap.isOpened():
  18. print("Error: Could not access the camera.")
  19. exit()
  20. print("Camera accessed successfully.")
  21. while True:
  22. ret, frame = cap.read()
  23. if not ret:
  24. print("Failed to grab frame.")
  25. break
  26. # Decode the QR code in the frame
  27. decoded_objects = decode(frame)
  28. if decoded_objects:
  29. print(f"Decoded {len(decoded_objects)} QR code(s).")
  30. for obj in decoded_objects:
  31. qr_data = obj.data.decode('utf-8')
  32. print(f"QR Code detected, data: {qr_data}")
  33. # Check if the QR code content is "hydrosense"
  34. if qr_data == "hydrosense":
  35. audio_file_path = "/home/pi/audio/hydrosense.mp3" # Modify this path if needed
  36. play_audio(audio_file_path)
  37. # Display the frame
  38. cv2.imshow("QR Code Scanner", frame)
  39. # Break the loop if 'q' is pressed
  40. if cv2.waitKey(1) & 0xFF == ord('q'):
  41. print("Exiting.")
  42. break
  43. # Release the capture and close windows
  44. cap.release()
  45. cv2.destroyAllWindows()
  46. print("Camera released and windows closed.")