WorkWithCam.py 3.9 KB

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