USBCam.py 3.8 KB

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