aboutsummaryrefslogtreecommitdiffstats
path: root/examples/multimedia/camera/camera.py
blob: bbcba0b0235e44e5eca166401f27297500c8cd13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

"""PySide6 Multimedia Camera Example"""

import os
import sys
from PySide6.QtCore import QDate, QDir, QStandardPaths, Qt, QUrl, Slot
from PySide6.QtGui import QAction, QGuiApplication, QDesktopServices, QIcon
from PySide6.QtGui import QImage, QPixmap
from PySide6.QtWidgets import (QApplication, QHBoxLayout, QLabel,
    QMainWindow, QPushButton, QTabWidget, QToolBar, QVBoxLayout, QWidget)
from PySide6.QtMultimedia import (QCamera, QImageCapture,
                                  QCameraDevice, QMediaCaptureSession,
                                  QMediaDevices)
from PySide6.QtMultimediaWidgets import QVideoWidget


class ImageView(QWidget):
    def __init__(self, previewImage, fileName):
        super().__init__()

        self._file_name = fileName

        main_layout = QVBoxLayout(self)
        self._image_label = QLabel()
        self._image_label.setPixmap(QPixmap.fromImage(previewImage))
        main_layout.addWidget(self._image_label)

        top_layout = QHBoxLayout()
        self._file_name_label = QLabel(QDir.toNativeSeparators(fileName))
        self._file_name_label.setTextInteractionFlags(Qt.TextBrowserInteraction)

        top_layout.addWidget(self._file_name_label)
        top_layout.addStretch()
        copy_button = QPushButton("Copy")
        copy_button.setToolTip("Copy file name to clipboard")
        top_layout.addWidget(copy_button)
        copy_button.clicked.connect(self.copy)
        launch_button = QPushButton("Launch")
        launch_button.setToolTip("Launch image viewer")
        top_layout.addWidget(launch_button)
        launch_button.clicked.connect(self.launch)
        main_layout.addLayout(top_layout)

    @Slot()
    def copy(self):
        QGuiApplication.clipboard().setText(self._file_name_label.text())

    @Slot()
    def launch(self):
        QDesktopServices.openUrl(QUrl.fromLocalFile(self._file_name))


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self._capture_session = None
        self._camera = None
        self._camera_info = None
        self._image_capture = None

        available_cameras = QMediaDevices.videoInputs()
        if available_cameras:
            self._camera_info = available_cameras[0]
            self._camera = QCamera(self._camera_info)
            self._camera.errorOccurred.connect(self._camera_error)
            self._image_capture = QImageCapture(self._camera)
            self._image_capture.imageCaptured.connect(self.image_captured)
            self._image_capture.imageSaved.connect(self.image_saved)
            self._image_capture.errorOccurred.connect(self._capture_error)
            self._capture_session = QMediaCaptureSession()
            self._capture_session.setCamera(self._camera)
            self._capture_session.setImageCapture(self._image_capture)

        self._current_preview = QImage()

        tool_bar = QToolBar()
        self.addToolBar(tool_bar)

        file_menu = self.menuBar().addMenu("&File")
        shutter_icon = QIcon(os.path.join(os.path.dirname(__file__),
                            "shutter.svg"))
        self._take_picture_action = QAction(shutter_icon, "&Take Picture", self,
                                            shortcut="Ctrl+T",
                                            triggered=self.take_picture)
        self._take_picture_action.setToolTip("Take Picture")
        file_menu.addAction(self._take_picture_action)
        tool_bar.addAction(self._take_picture_action)

        exit_action = QAction(QIcon.fromTheme("application-exit"), "E&xit",
                              self, shortcut="Ctrl+Q", triggered=self.close)
        file_menu.addAction(exit_action)

        about_menu = self.menuBar().addMenu("&About")
        about_qt_action = QAction("About &Qt", self, triggered=qApp.aboutQt)
        about_menu.addAction(about_qt_action)

        self._tab_widget = QTabWidget()
        self.setCentralWidget(self._tab_widget)

        self._camera_viewfinder = QVideoWidget()
        self._tab_widget.addTab(self._camera_viewfinder, "Viewfinder")

        if self._camera and self._camera.error() == QCamera.NoError:
            name = self._camera_info.description()
            self.setWindowTitle(f"PySide6 Camera Example ({name})")
            self.show_status_message(f"Starting: '{name}'")
            self._capture_session.setVideoOutput(self._camera_viewfinder)
            self._take_picture_action.setEnabled(self._image_capture.isReadyForCapture())
            self._image_capture.readyForCaptureChanged.connect(self._take_picture_action.setEnabled)
            self._camera.start()
        else:
            self.setWindowTitle("PySide6 Camera Example")
            self._take_picture_action.setEnabled(False)
            self.show_status_message("Camera unavailable")

    def show_status_message(self, message):
        self.statusBar().showMessage(message, 5000)

    def closeEvent(self, event):
        if self._camera and self._camera.isActive():
            self._camera.stop()
        event.accept()

    def next_image_file_name(self):
        pictures_location = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation)
        date_string = QDate.currentDate().toString("yyyyMMdd")
        pattern = f"{pictures_location}/pyside6_camera_{date_string}_{{:03d}}.jpg"
        n = 1
        while True:
            result = pattern.format(n)
            if not os.path.exists(result):
                return result
            n = n + 1
        return None

    @Slot()
    def take_picture(self):
        self._current_preview = QImage()
        self._image_capture.captureToFile(self.next_image_file_name())

    @Slot(int, QImage)
    def image_captured(self, id, previewImage):
        self._current_preview = previewImage

    @Slot(int, str)
    def image_saved(self, id, fileName):
        index = self._tab_widget.count()
        image_view = ImageView(self._current_preview, fileName)
        self._tab_widget.addTab(image_view, f"Capture #{index}")
        self._tab_widget.setCurrentIndex(index)

    @Slot(int, QImageCapture.Error, str)
    def _capture_error(self, id, error, error_string):
        print(error_string, file=sys.stderr)
        self.show_status_message(error_string)

    @Slot(QCamera.Error, str)
    def _camera_error(self, error, error_string):
        print(error_string, file=sys.stderr)
        self.show_status_message(error_string)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_win = MainWindow()
    available_geometry = main_win.screen().availableGeometry()
    main_win.resize(available_geometry.width() / 3, available_geometry.height() / 2)
    main_win.show()
    sys.exit(app.exec())