USBCam.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import os, sys
  2. from PySide6.QtMultimediaWidgets import QVideoWidget
  3. from PySide6.QtCore import Slot
  4. from PySide6.QtGui import QImage
  5. from PySide6.QtWidgets import QLabel
  6. from PySide6.QtMultimedia import (
  7. QMediaDevices, QCamera, QImageCapture, QMediaCaptureSession)
  8. from itertools import groupby
  9. from logger import logger
  10. from module import create_filename
  11. from widgets import ImageViewer
  12. if not os.environ.get("PHOTO_DIR"):
  13. logger.error("Не задана локальная переменная PHOTO_DIR")
  14. raise ValueError(
  15. "не задана локальная переменная PHOTO_DIR"
  16. )
  17. class USBCam:
  18. _capture_session: QMediaCaptureSession
  19. _camera: QCamera
  20. _camera_info: list[QMediaDevices]
  21. _image_capture: QImageCapture
  22. _current_preview: QImage = QImage()
  23. _label: QLabel
  24. _video_widget: QVideoWidget
  25. def __init__(self, video_widget: QVideoWidget, name_cam: str) -> None:
  26. self._create_dirs()
  27. self._video_widget = video_widget
  28. self._camera_info = get_object_cam_by_name(name_cam)
  29. if not self._camera_info:
  30. logger.error(
  31. "Не нашли камеру убидитесь, что у вас есть камера")
  32. sys.exit(0)
  33. def start_cam(self):
  34. self._camera = QCamera(self._camera_info)
  35. self._camera.errorOccurred.connect(self._camera_error)
  36. self._image_capture = QImageCapture(self._camera)
  37. self._image_capture.imageCaptured.connect(self.image_captured)
  38. self._image_capture.imageSaved.connect(self.image_saved)
  39. self._image_capture.errorOccurred.connect(self._capture_error)
  40. self._capture_session = QMediaCaptureSession()
  41. self._capture_session.setCamera(self._camera)
  42. self._capture_session.setImageCapture(self._image_capture)
  43. if self._camera and self._camera.error() == QCamera.NoError:
  44. self._capture_session.setVideoOutput(self._video_widget)
  45. self._camera.start()
  46. else:
  47. logger.error("Camera unavailable")
  48. def stop_cam(self) -> None:
  49. try:
  50. if self._camera and self._camera.isActive():
  51. self._camera.stop()
  52. except RuntimeError as err:
  53. logger.error(err)
  54. def __del__(self) -> None:
  55. self.stop_cam()
  56. def cupture_image(self, image_viewer: ImageViewer) -> str:
  57. self._image_viewer = image_viewer
  58. self._file_name = create_filename()
  59. self._image_capture.captureToFile(self._file_name)
  60. logger.info(F"Создаем файл {self._file_name}")
  61. return self._file_name
  62. @Slot(int, QImageCapture.Error, str)
  63. def _capture_error(self, id, error, error_string):
  64. logger.error(error_string)
  65. @Slot(QCamera.Error, str)
  66. def _camera_error(self, error, error_string):
  67. logger.error(error_string)
  68. def _create_dirs(self):
  69. if not os.path.exists(os.environ.get('PHOTO_DIR')):
  70. os.mkdir(os.environ.get('PHOTO_DIR'))
  71. @Slot(int, QImage)
  72. def image_captured(self, id, previewImage):
  73. self._current_preview = previewImage
  74. @Slot(int, str)
  75. def image_saved(self, id, fileName):
  76. self._image_viewer.setImage(fileName)
  77. self.stop_cam()
  78. return fileName
  79. def get_first_cam() -> str:
  80. try:
  81. return QMediaDevices.videoInputs()[0].description()
  82. except IndexError:
  83. pass
  84. def get_list_name_cam() -> list[str]:
  85. return [x for x, _ in groupby(
  86. [x.description() for x in QMediaDevices.videoInputs()]
  87. )]
  88. def get_object_cam_by_name(name_cam: str) -> QMediaDevices:
  89. return [x for x in QMediaDevices.videoInputs() if x.description() == name_cam][0]