WorkWithCam.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 appdirs import user_data_dir
  10. from datetime import datetime
  11. from itertools import groupby
  12. if os.environ.get("PHOTO_DIR"):
  13. IMAGES_PATH = os.environ.get("PHOTO_DIR")
  14. else:
  15. raise ValueError(
  16. "не задана локальная переменная PHOTO_DIR"
  17. )
  18. class WorkWithCam:
  19. def __init__(self, q_Video_Widget: QVideoWidget, name_cam: str) -> None:
  20. self._create_dirs()
  21. self._capture_session = None
  22. self._camera = None
  23. self._camera_info = None
  24. self._image_capture = None
  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. raise IndexError(
  29. f"Не нашли камеру QMediaDevices.videoInputs(). убидитесь, что у вас есть камера")
  30. self._file_name = self.get_filename()
  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. # print()
  43. name = self._camera_info.description()
  44. self._capture_session.setVideoOutput(self._video_widget)
  45. self._camera.start()
  46. else:
  47. print("Camera unavailable")
  48. def stop_cam(self) -> None:
  49. if self._camera and self._camera.isActive():
  50. self._camera.stop()
  51. def __del__(self) -> None:
  52. self.stop_cam()
  53. def cupture_image(self) -> str:
  54. self._current_preview = QImage()
  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. print(error_string, file=sys.stderr)
  60. self.show_status_message(error_string)
  61. @Slot(QCamera.Error, str)
  62. def _camera_error(self, error, error_string):
  63. print(error_string, file=sys.stderr)
  64. self.show_status_message(error_string)
  65. @staticmethod
  66. def get_filename() -> str:
  67. return F"{IMAGES_PATH}/propusk_{datetime.now().timestamp()}.jpg"
  68. def _create_dirs(self):
  69. if not os.path.exists(IMAGES_PATH):
  70. os.mkdir(IMAGES_PATH)
  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. ...
  77. def show_status_message(self, message):
  78. print(message, 5000)
  79. def load_image(qlabel: QLabel, path_file: str) -> None:
  80. qlabel.setPixmap(QPixmap(QImage(path_file)).scaled(
  81. qlabel.width()-4,
  82. qlabel.height(),
  83. Qt.AspectRatioMode.KeepAspectRatio,
  84. Qt.TransformationMode.FastTransformation
  85. ))
  86. def get_list_name_cam() -> list:
  87. return [x for x, _ in groupby(
  88. [x.description() for x in QMediaDevices.videoInputs()]
  89. )]
  90. def get_object_cam_by_name(name_cam: str) -> QMediaDevices:
  91. return [x for x in QMediaDevices.videoInputs() if x.description() == name_cam][0]