datamatrix_playground.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from picamera2 import Picamera2
  2. import cv2
  3. from pylibdmtx.pylibdmtx import decode
  4. # Initialize camera
  5. picam2 = Picamera2()
  6. picam2.configure(picam2.create_preview_configuration(main={"format": "BGR888", "size": (640, 480)}))
  7. picam2.start()
  8. # Your configured ROI
  9. x, y, w, h = 100, 0, 260, 450 # replace with your new values
  10. print("Press Enter to capture and decode a frame. Ctrl+C to exit.")
  11. while True:
  12. input("Capture frame now...")
  13. # Capture frame
  14. frame = picam2.capture_array()
  15. # Crop to ROI
  16. roi = frame[y:y+h, x:x+w]
  17. # Convert to grayscale + enhance contrast
  18. gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
  19. gray = cv2.equalizeHist(gray)
  20. # Optional: save the cropped ROI to check visually
  21. cv2.imwrite("roi_test.jpg", gray)
  22. # Decode DataMatrix
  23. decoded = decode(gray)
  24. if decoded:
  25. print("DataMatrix detected!")
  26. for d in decoded:
  27. print("Decoded content:", d.data.decode('utf-8'))
  28. else:
  29. print("No DataMatrix detected in this frame.")
  30. picam2.stop()