datamatrix_playground.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from picamera2 import Picamera2
  2. import cv2
  3. import time
  4. from pylibdmtx.pylibdmtx import decode
  5. from robot_control.src.api.gpio import PiGPIO, MockGPIO
  6. # Initialize GPIO
  7. gpio = PiGPIO(out_pins=[13]) # or MockGPIO() for testing
  8. # Initialize camera
  9. picam2 = Picamera2()
  10. picam2.configure(picam2.create_preview_configuration(main={"format": "BGR888", "size": (640, 480)}))
  11. picam2.start()
  12. # Your configured ROI
  13. x, y, w, h = 100, 0, 260, 450 # replace with your new values
  14. # Move servo to start position
  15. gpio.set_servo_angle_smooth(13, 15, 500)
  16. time.sleep(2)
  17. gpio.set_servo_angle_smooth(13, 88, 500)
  18. print("Press Enter to capture and decode a frame. Ctrl+C to exit.")
  19. try:
  20. while True:
  21. input("Capture frame now...")
  22. # Capture frame
  23. frame = picam2.capture_array()
  24. # Crop to ROI
  25. roi = frame[y:y+h, x:x+w]
  26. # Convert to grayscale + enhance contrast
  27. gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
  28. gray = cv2.equalizeHist(gray)
  29. # Optional: save the cropped ROI to check visually
  30. cv2.imwrite("roi_test.jpg", gray)
  31. # Decode DataMatrix
  32. decoded = decode(gray)
  33. if decoded:
  34. print("DataMatrix detected!")
  35. for d in decoded:
  36. print("Decoded content:", d.data.decode('utf-8'))
  37. else:
  38. print("No DataMatrix detected in this frame.")
  39. except KeyboardInterrupt:
  40. print("\nExiting...")
  41. finally:
  42. picam2.stop()
  43. gpio.cleanup()