datamatrix.py 2.1 KB

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