USBCam.py 4.0 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 import create_filename
  11. from module.ImageTool import cupture_face
  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()
  23. _label: QLabel
  24. def __init__(self, q_Video_Widget: QVideoWidget, name_cam: str) -> None:
  25. self._create_dirs()
  26. self._video_widget = q_Video_Widget
  27. self._camera_info = get_object_cam_by_name(name_cam)
  28. if not self._camera_info:
  29. logger.error(
  30. "Не нашли камеру QMediaDevices.videoInputs(). убидитесь, что у вас есть камера")
  31. raise IndexError(
  32. "Не нашли камеру QMediaDevices.videoInputs(). убидитесь, что у вас есть камера")
  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, label: QLabel) -> str:
  57. self._label = label
  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. load_image(self._label, fileName)
  77. self.stop_cam()
  78. cupture_face(fileName, F"face_{create_filename()}")
  79. def load_image(qlabel: QLabel, path_file: str) -> None:
  80. logger.info(F"Set image to label: {path_file}")
  81. qlabel.setPixmap(QPixmap(QImage(path_file)).scaled(
  82. qlabel.width()-4,
  83. qlabel.height(),
  84. Qt.AspectRatioMode.KeepAspectRatio,
  85. Qt.TransformationMode.FastTransformation
  86. ))
  87. def get_list_name_cam() -> list:
  88. return [x for x, _ in groupby(
  89. [x.description() for x in QMediaDevices.videoInputs()]
  90. )]
  91. def get_object_cam_by_name(name_cam: str) -> QMediaDevices:
  92. return [x for x in QMediaDevices.videoInputs() if x.description() == name_cam][0]