datamatrix.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import cv2
  2. from pylibdmtx.pylibdmtx import decode
  3. import logging
  4. import os
  5. from pathlib import Path
  6. logger = logging.getLogger(__name__)
  7. class TestCamera:
  8. def __init__(self, test_files_path: str):
  9. self.image_files = []
  10. self.current_index = 0
  11. # Load all image files from the test directory
  12. path = Path(test_files_path)
  13. if path.exists() and path.is_dir():
  14. self.image_files = sorted([
  15. str(f) for f in path.glob("*")
  16. if f.suffix.lower() in ['.png', '.jpg', '.jpeg']
  17. ])
  18. if not self.image_files:
  19. logger.warning(f"No image files found in {test_files_path}")
  20. else:
  21. logger.error(f"Test files directory not found: {test_files_path}")
  22. def read(self):
  23. if not self.image_files:
  24. return False, None
  25. # Read next image file in sequence
  26. image_path = self.image_files[self.current_index]
  27. frame = cv2.imread(image_path)
  28. if frame is None:
  29. logger.error(f"Failed to load image: {image_path}")
  30. return False, None
  31. # Cycle through available images
  32. self.current_index = (self.current_index + 1) % len(self.image_files)
  33. return True, frame
  34. def release(self):
  35. pass
  36. class DataMatrixReader:
  37. def __init__(self, camera_id: int = 0):
  38. self.camera_id = camera_id
  39. self.camera = None
  40. def initialize(self):
  41. if self.camera_id < 0:
  42. test_path = "robot-control/tests/files/"
  43. self.camera = TestCamera(test_path)
  44. else:
  45. self.camera = cv2.VideoCapture(self.camera_id)
  46. def read_datamatrix(self) -> str:
  47. ret, frame = self.camera.read()
  48. if not ret:
  49. raise Exception("Failed to capture image")
  50. decoded = decode(frame)
  51. if not decoded:
  52. logger.error("No datamatrix found")
  53. return None
  54. return decoded[0].data.decode('utf-8')
  55. def cleanup(self):
  56. if self.camera:
  57. self.camera.release()