USBCam.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import os
  2. from PySide6.QtMultimediaWidgets import QVideoWidget
  3. from PySide6.QtCore import Slot, Qt
  4. from PySide6.QtGui import QImage, QPixmap
  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.ImageTool import create_filename
  11. if not os.environ.get("PHOTO_DIR"):
  12. logger.error("Не задана локальная переменная PHOTO_DIR")
  13. raise ValueError(
  14. "не задана локальная переменная PHOTO_DIR"
  15. )
  16. class USBCam:
  17. _capture_session: QMediaCaptureSession
  18. _camera: QCamera
  19. _camera_info: list[QMediaDevices]
  20. _image_capture: QImageCapture
  21. _current_preview = QImage()
  22. _label: QLabel
  23. def __init__(self, q_Video_Widget: QVideoWidget, name_cam: str) -> None:
  24. self._create_dirs()
  25. self._video_widget = q_Video_Widget
  26. self._camera_info = get_object_cam_by_name(name_cam)
  27. if not self._camera_info:
  28. logger.error("Не нашли камеру QMediaDevices.videoInputs(). убидитесь, что у вас есть камера")
  29. raise IndexError(
  30. "Не нашли камеру QMediaDevices.videoInputs(). убидитесь, что у вас есть камера")
  31. def start_cam(self):
  32. self._camera = QCamera(self._camera_info)
  33. self._camera.errorOccurred.connect(self._camera_error)
  34. self._image_capture = QImageCapture(self._camera)
  35. self._image_capture.imageCaptured.connect(self.image_captured)
  36. self._image_capture.imageSaved.connect(self.image_saved)
  37. self._image_capture.errorOccurred.connect(self._capture_error)
  38. self._capture_session = QMediaCaptureSession()
  39. self._capture_session.setCamera(self._camera)
  40. self._capture_session.setImageCapture(self._image_capture)
  41. if self._camera and self._camera.error() == QCamera.NoError:
  42. self._capture_session.setVideoOutput(self._video_widget)
  43. self._camera.start()
  44. else:
  45. logger.error("Camera unavailable")
  46. def stop_cam(self) -> None:
  47. try:
  48. if self._camera and self._camera.isActive():
  49. self._camera.stop()
  50. except RuntimeError as err:
  51. logger.error(err)
  52. def __del__(self) -> None:
  53. self.stop_cam()
  54. def cupture_image(self, label: QLabel) -> str:
  55. self._label = label
  56. self._file_name = create_filename()
  57. self._image_capture.captureToFile(self._file_name)
  58. logger.info(F"Создаем файл {self._file_name}")
  59. return self._file_name
  60. @Slot(int, QImageCapture.Error, str)
  61. def _capture_error(self, id, error, error_string):
  62. logger.error(error_string)
  63. @Slot(QCamera.Error, str)
  64. def _camera_error(self, error, error_string):
  65. logger.error(error_string)
  66. def _create_dirs(self):
  67. if not os.path.exists(os.environ.get('PHOTO_DIR')):
  68. os.mkdir(os.environ.get('PHOTO_DIR'))
  69. @Slot(int, QImage)
  70. def image_captured(self, id, previewImage):
  71. self._current_preview = previewImage
  72. @Slot(int, str)
  73. def image_saved(self, id, fileName):
  74. load_image(self._label, fileName)
  75. self.stop_cam()
  76. def load_image(qlabel: QLabel, path_file: str) -> None:
  77. logger.info(F"Set image to label: {path_file}")
  78. qlabel.setPixmap(QPixmap(QImage(path_file)).scaled(
  79. qlabel.width()-4,
  80. qlabel.height(),
  81. Qt.AspectRatioMode.KeepAspectRatio,
  82. Qt.TransformationMode.FastTransformation
  83. ))
  84. def get_list_name_cam() -> list:
  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]