testcamera.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import cv2
  2. from picamera2 import Picamera2
  3. from pyzbar.pyzbar import decode
  4. import pygame
  5. import time
  6. # Initialize the camera and pygame for playing audio
  7. picam2 = Picamera2()
  8. picam2.start()
  9. pygame.mixer.init()
  10. def play_audio(mp3_file):
  11. """Plays the specified MP3 file."""
  12. try:
  13. pygame.mixer.music.load(mp3_file)
  14. pygame.mixer.music.play()
  15. while pygame.mixer.music.get_busy():
  16. time.sleep(1)
  17. except Exception as e:
  18. print(f"Error playing audio: {e}")
  19. def scan_qr_code(image):
  20. """Scans the QR code from the given image and returns the decoded data."""
  21. qr_codes = decode(image)
  22. if qr_codes:
  23. # Extract the string from the QR code
  24. qr_data = qr_codes[0].data.decode('utf-8')
  25. print("QR Code detected:", qr_data)
  26. return qr_data
  27. return None
  28. while True:
  29. # Capture an image from the camera
  30. image = picam2.capture_array()
  31. # Convert the image to grayscale (QR code scanning works better in grayscale)
  32. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  33. # Scan for QR code in the image
  34. qr_data = scan_qr_code(gray)
  35. if qr_data:
  36. # If QR code contains "hydrosense", play the corresponding MP3
  37. if qr_data.lower() == "hydrosense": # Case insensitive comparison
  38. print("Playing Hydrosense.mp3")
  39. play_audio("Hydrosense.mp3") # Make sure the MP3 file is in the correct path
  40. # Display the image (for debugging purposes)
  41. cv2.imshow('QR Code Scanner', image)
  42. # Exit the loop if 'q' is pressed
  43. if cv2.waitKey(1) & 0xFF == ord('q'):
  44. break
  45. # Cleanup
  46. picam2.stop()
  47. cv2.destroyAllWindows()
  48. pygame.quit()