Пример #1
0
class QrReaderCameraDialog(Logger, MessageBoxMixin, QDialog):
    """
    Dialog for reading QR codes from a camera
    """

    # Try to crop so we have minimum 512 dimensions
    SCAN_SIZE: int = 512

    qr_finished = pyqtSignal(bool, str, object)

    def __init__(self, parent, *, config: SimpleConfig):
        ''' Note: make sure parent is a "top_level_window()" as per
        MessageBoxMixin API else bad things can happen on macOS. '''
        QDialog.__init__(self, parent=parent)
        Logger.__init__(self)

        self.validator: AbstractQrReaderValidator = None
        self.frame_id: int = 0
        self.qr_crop: QRect = None
        self.qrreader_res: List[QrCodeResult] = []
        self.validator_res: QrReaderValidatorResult = None
        self.last_stats_time: float = 0.0
        self.frame_counter: int = 0
        self.qr_frame_counter: int = 0
        self.last_qr_scan_ts: float = 0.0
        self.camera: QCamera = None
        self._error_message: str = None
        self._ok_done: bool = False
        self.camera_sc_conn = None
        self.resolution: QSize = None

        self.config = config

        # Try to get the QR reader for this system
        self.qrreader = get_qr_reader()
        if not self.qrreader:
            raise MissingQrDetectionLib(
                _("The platform QR detection library is not available."))

        # Set up the window, add the maximize button
        flags = self.windowFlags()
        flags = flags | Qt.WindowMaximizeButtonHint
        self.setWindowFlags(flags)
        self.setWindowTitle(_("Scan QR Code"))
        self.setWindowModality(
            Qt.WindowModal if parent else Qt.ApplicationModal)

        # Create video widget and fixed aspect ratio layout to contain it
        self.video_widget = QrReaderVideoWidget()
        self.video_overlay = QrReaderVideoOverlay()
        self.video_layout = FixedAspectRatioLayout()
        self.video_layout.addWidget(self.video_widget)
        self.video_layout.addWidget(self.video_overlay)

        # Create root layout and add the video widget layout to it
        vbox = QVBoxLayout()
        self.setLayout(vbox)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.addLayout(self.video_layout)

        self.lowres_label = QLabel(
            _("Note: This camera generates frames of relatively low resolution; QR scanning accuracy may be affected"
              ))
        self.lowres_label.setWordWrap(True)
        self.lowres_label.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
        vbox.addWidget(self.lowres_label)
        self.lowres_label.setHidden(True)

        # Create a layout for the controls
        controls_layout = QHBoxLayout()
        controls_layout.addStretch(2)
        controls_layout.setContentsMargins(10, 10, 10, 10)
        controls_layout.setSpacing(10)
        vbox.addLayout(controls_layout)

        # Flip horizontally checkbox with default coming from global config
        self.flip_x = QCheckBox()
        self.flip_x.setText(_("&Flip horizontally"))
        self.flip_x.setChecked(bool(self.config.get('qrreader_flip_x', True)))
        self.flip_x.stateChanged.connect(self._on_flip_x_changed)
        controls_layout.addWidget(self.flip_x)

        close_but = QPushButton(_("&Close"))
        close_but.clicked.connect(self.reject)
        controls_layout.addWidget(close_but)

        # Create the video surface and receive events when new frames arrive
        self.video_surface = QrReaderVideoSurface(self)
        self.video_surface.frame_available.connect(self._on_frame_available)

        # Create the crop blur effect
        self.crop_blur_effect = QrReaderCropBlurEffect(self)
        self.image_effect = ImageGraphicsEffect(self, self.crop_blur_effect)

        # Note these should stay as queued connections becasue we use the idiom
        # self.reject() and self.accept() in this class to kill the scan --
        # and we do it from within callback functions. If you don't use
        # queued connections here, bad things can happen.
        self.finished.connect(self._boilerplate_cleanup, Qt.QueuedConnection)
        self.finished.connect(self._on_finished, Qt.QueuedConnection)

    def _on_flip_x_changed(self, _state: int):
        self.config.set_key('qrreader_flip_x', self.flip_x.isChecked())

    def _get_resolution(self, resolutions: List[QSize],
                        min_size: int) -> QSize:
        """
        Given a list of resolutions that the camera supports this function picks the
        lowest resolution that is at least min_size in both width and height.
        If no resolution is found, NoCameraResolutionsFound is raised.
        """
        def res_list_to_str(res_list: List[QSize]) -> str:
            return ', '.join(
                ['{}x{}'.format(r.width(), r.height()) for r in res_list])

        def check_res(res: QSize):
            return res.width() >= min_size and res.height() >= min_size

        self.logger.info('searching for at least {0}x{0}'.format(min_size))

        # Query and display all resolutions the camera supports
        format_str = 'camera resolutions: {}'
        self.logger.info(format_str.format(res_list_to_str(resolutions)))

        # Filter to those that are at least min_size in both width and height
        candidate_resolutions = []
        ideal_resolutions = [r for r in resolutions if check_res(r)]
        less_than_ideal_resolutions = [
            r for r in resolutions if r not in ideal_resolutions
        ]
        format_str = 'ideal resolutions: {}, less-than-ideal resolutions: {}'
        self.logger.info(
            format_str.format(res_list_to_str(ideal_resolutions),
                              res_list_to_str(less_than_ideal_resolutions)))

        # Raise an error if we have no usable resolutions
        if not ideal_resolutions and not less_than_ideal_resolutions:
            raise NoCameraResolutionsFound(
                _("Cannot start QR scanner, no usable camera resolution found."
                  ) + self._linux_pyqt5bug_msg())

        if not ideal_resolutions:
            self.logger.warning(
                'No ideal resolutions found, falling back to less-than-ideal resolutions -- QR recognition may fail!'
            )
            candidate_resolutions = less_than_ideal_resolutions
            is_ideal = False
        else:
            candidate_resolutions = ideal_resolutions
            is_ideal = True

        # Sort the usable resolutions, least number of pixels first, get the first element
        resolution = sorted(candidate_resolutions,
                            key=lambda r: r.width() * r.height(),
                            reverse=not is_ideal)[0]
        format_str = 'chosen resolution is {}x{}'
        self.logger.info(
            format_str.format(resolution.width(), resolution.height()))

        return resolution, is_ideal

    @staticmethod
    def _get_crop(resolution: QSize, scan_size: int) -> QRect:
        """
        Returns a QRect that is scan_size x scan_size in the middle of the resolution
        """
        scan_pos_x = (resolution.width() - scan_size) // 2
        scan_pos_y = (resolution.height() - scan_size) // 2
        return QRect(scan_pos_x, scan_pos_y, scan_size, scan_size)

    @staticmethod
    def _linux_pyqt5bug_msg():
        ''' Returns a string that may be appended to an exception error message
        only if on Linux and PyQt5 < 5.12.2, otherwise returns an empty string. '''
        if (sys.platform == 'linux'
                and PYQT_VERSION < 0x050c02  # Check if PyQt5 < 5.12.2 on linux
                # Also: this warning is not relevant to APPIMAGE; so make sure
                # we are not running from APPIMAGE.
                and not os.environ.get('APPIMAGE')):
            # In this case it's possible we couldn't detect a camera because
            # of that missing libQt5MultimediaGstTools.so problem.
            return ("\n\n" + _(
                'If you indeed do have a usable camera connected, then this error may be caused by bugs in previous PyQt5 versions on Linux. Try installing the latest PyQt5:'
            ) + "\n\n" + "python3 -m pip install --user -I pyqt5")
        return ''

    def start_scan(self, device: str = ''):
        """
        Scans a QR code from the given camera device.
        If no QR code is found the returned string will be empty.
        If the camera is not found or can't be opened NoCamerasFound will be raised.
        """

        self.validator = QrReaderValidatorCounted()
        self.validator.strong_count = 5  # FIXME: make this time based rather than framect based

        device_info = None

        for camera in QCameraInfo.availableCameras():
            if camera.deviceName() == device:
                device_info = camera
                break

        if not device_info:
            self.logger.info(
                'Failed to open selected camera, trying to use default camera')
            device_info = QCameraInfo.defaultCamera()

        if not device_info or device_info.isNull():
            raise NoCamerasFound(
                _("Cannot start QR scanner, no usable camera found.") +
                self._linux_pyqt5bug_msg())

        self._init_stats()
        self.qrreader_res = []
        self.validator_res = None
        self._ok_done = False
        self._error_message = None

        if self.camera:
            self.logger.info(
                "Warning: start_scan already called for this instance.")

        self.camera = QCamera(device_info)
        self.camera.setViewfinder(self.video_surface)
        self.camera.setCaptureMode(QCamera.CaptureViewfinder)

        # this operates on camera from within the signal handler, so should be a queued connection
        self.camera_sc_conn = self.camera.statusChanged.connect(
            self._on_camera_status_changed, Qt.QueuedConnection)
        self.camera.error.connect(
            self._on_camera_error
        )  # log the errors we get, if any, for debugging
        # Camera needs to be loaded to query resolutions, this tries to open the camera
        self.camera.load()

    _camera_status_names = {
        QCamera.UnavailableStatus: _('unavailable'),
        QCamera.UnloadedStatus: _('unloaded'),
        QCamera.UnloadingStatus: _('unloading'),
        QCamera.LoadingStatus: _('loading'),
        QCamera.LoadedStatus: _('loaded'),
        QCamera.StandbyStatus: _('standby'),
        QCamera.StartingStatus: _('starting'),
        QCamera.StoppingStatus: _('stopping'),
        QCamera.ActiveStatus: _('active')
    }

    def _get_camera_status_name(self, status: QCamera.Status):
        return self._camera_status_names.get(status, _('unknown'))

    def _set_resolution(self, resolution: QSize):
        self.resolution = resolution
        self.qr_crop = self._get_crop(resolution, self.SCAN_SIZE)

        # Initialize the video widget
        #self.video_widget.setMinimumSize(resolution)  # <-- on macOS this makes it fixed size for some reason.
        self.resize(720, 540)
        self.video_overlay.set_crop(self.qr_crop)
        self.video_overlay.set_resolution(resolution)
        self.video_layout.set_aspect_ratio(resolution.width() /
                                           resolution.height())

        # Set up the crop blur effect
        self.crop_blur_effect.setCrop(self.qr_crop)

    def _on_camera_status_changed(self, status: QCamera.Status):
        if self._ok_done:
            # camera/scan is quitting, abort.
            return

        self.logger.info('camera status changed to {}'.format(
            self._get_camera_status_name(status)))

        if status == QCamera.LoadedStatus:
            # Determine the optimal resolution and compute the crop rect
            camera_resolutions = self.camera.supportedViewfinderResolutions()
            try:
                resolution, was_ideal = self._get_resolution(
                    camera_resolutions, self.SCAN_SIZE)
            except RuntimeError as e:
                self._error_message = str(e)
                self.reject()
                return
            self._set_resolution(resolution)

            # Set the camera resolution
            viewfinder_settings = QCameraViewfinderSettings()
            viewfinder_settings.setResolution(resolution)
            self.camera.setViewfinderSettings(viewfinder_settings)

            # Counter for the QR scanner frame number
            self.frame_id = 0

            self.camera.start()
            self.lowres_label.setVisible(
                not was_ideal
            )  # if they have a low res camera, show the warning label.
        elif status == QCamera.UnloadedStatus or status == QCamera.UnavailableStatus:
            self._error_message = _(
                "Cannot start QR scanner, camera is unavailable.")
            self.reject()
        elif status == QCamera.ActiveStatus:
            self.open()

    CameraErrorStrings = {
        QCamera.NoError: "No Error",
        QCamera.CameraError: "Camera Error",
        QCamera.InvalidRequestError: "Invalid Request Error",
        QCamera.ServiceMissingError: "Service Missing Error",
        QCamera.NotSupportedFeatureError: "Unsupported Feature Error"
    }

    def _on_camera_error(self, errorCode):
        errStr = self.CameraErrorStrings.get(errorCode, "Unknown Error")
        self.logger.info(f"QCamera error: {errStr}")

    def accept(self):
        self._ok_done = True  # immediately blocks further processing
        super().accept()

    def reject(self):
        self._ok_done = True  # immediately blocks further processing
        super().reject()

    def _boilerplate_cleanup(self):
        self._close_camera()
        if self.isVisible():
            self.close()

    def _close_camera(self):
        if self.camera:
            self.camera.setViewfinder(None)
            if self.camera_sc_conn:
                self.camera.statusChanged.disconnect(self.camera_sc_conn)
                self.camera_sc_conn = None
            self.camera.unload()
            self.camera = None

    def _on_finished(self, code):
        res = ((code == QDialog.Accepted and self.validator_res
                and self.validator_res.accepted
                and self.validator_res.simple_result) or '')

        self.validator = None

        self.logger.info(f'closed {res}')

        self.qr_finished.emit(code == QDialog.Accepted, self._error_message,
                              res)

    def _on_frame_available(self, frame: QImage):
        if self._ok_done:
            return

        self.frame_id += 1

        if frame.size() != self.resolution:
            self.logger.info(
                'Getting video data at {}x{} instead of the requested {}x{}, switching resolution.'
                .format(frame.size().width(),
                        frame.size().height(), self.resolution.width(),
                        self.resolution.height()))
            self._set_resolution(frame.size())

        flip_x = self.flip_x.isChecked()

        # Only QR scan every QR_SCAN_PERIOD secs
        qr_scanned = time.time(
        ) - self.last_qr_scan_ts >= self.qrreader.interval()
        if qr_scanned:
            self.last_qr_scan_ts = time.time()
            # Crop the frame so we only scan a SCAN_SIZE rect
            frame_cropped = frame.copy(self.qr_crop)

            # Convert to Y800 / GREY FourCC (single 8-bit channel)
            # This creates a copy, so we don't need to keep the frame around anymore
            frame_y800 = frame_cropped.convertToFormat(
                QImage.Format_Grayscale8)

            # Read the QR codes from the frame
            self.qrreader_res = self.qrreader.read_qr_code(
                frame_y800.constBits().__int__(), frame_y800.byteCount(),
                frame_y800.bytesPerLine(), frame_y800.width(),
                frame_y800.height(), self.frame_id)

            # Call the validator to see if the scanned results are acceptable
            self.validator_res = self.validator.validate_results(
                self.qrreader_res)

            # Update the video overlay with the results
            self.video_overlay.set_results(self.qrreader_res, flip_x,
                                           self.validator_res)

            # Close the dialog if the validator accepted the result
            if self.validator_res.accepted:
                self.accept()
                return

        # Apply the crop blur effect
        if self.image_effect:
            frame = self.image_effect.apply(frame)

        # If horizontal flipping is enabled, only flip the display
        if flip_x:
            frame = frame.mirrored(True, False)

        # Display the frame in the widget
        self.video_widget.setPixmap(QPixmap.fromImage(frame))

        self._update_stats(qr_scanned)

    def _init_stats(self):
        self.last_stats_time = time.perf_counter()
        self.frame_counter = 0
        self.qr_frame_counter = 0

    def _update_stats(self, qr_scanned):
        self.frame_counter += 1
        if qr_scanned:
            self.qr_frame_counter += 1
        now = time.perf_counter()
        last_stats_delta = now - self.last_stats_time
        if last_stats_delta > 1.0:  # stats every 1.0 seconds
            fps = self.frame_counter / last_stats_delta
            qr_fps = self.qr_frame_counter / last_stats_delta
            if self.validator is not None:
                self.validator.strong_count = math.ceil(
                    qr_fps / 3
                )  # 1/3 of a second's worth of qr frames determines strong_count
            stats_format = 'running at {} FPS, scanner at {} FPS'
            self.logger.info(stats_format.format(fps, qr_fps))
            self.frame_counter = 0
            self.qr_frame_counter = 0
            self.last_stats_time = now
Пример #2
0
class CQCameraPreviewWindow(QtWidgets.QMainWindow):
    closeSignal = QtCore.pyqtSignal()
    ioctlRequest = QtCore.pyqtSignal(dict)

    def __init__(self, *args, **kwargs):
        super(CQCameraPreviewWindow, self).__init__(*args, **kwargs)

        self._MIN_WIN_WIDTH = 640
        self.oc_camera_info = None
        self.oc_camera = None
        self.b_guard = False
        self.toolbar = QtWidgets.QToolBar("Preview")

        self.cbox_resolution = CLabeledComboBox("Resolution:")
        self.cbox_resolution.cbox.currentIndexChanged.connect(self.__cb_on_resolution_cbox_index_changed)
        self.toolbar.addWidget(self.cbox_resolution)
        self.toolbar.addSeparator()

        self.cbox_frame_rate = CLabeledComboBox("Frame Rate:")
        self.cbox_frame_rate.cbox.currentIndexChanged.connect(self.__cb_on_frame_rate_cbox_index_changed)
        self.toolbar.addWidget(self.cbox_frame_rate)
        self.addToolBar(self.toolbar)
        self.toolbar.addSeparator()

        self.oc_view_finder = QCameraViewfinder()
        self.setCentralWidget(self.oc_view_finder)

    def __cb_on_resolution_cbox_index_changed(self, i_idx):
        if self.oc_camera is None:
            self.fatal_error("Unallocated camera object detected")
        if self.b_guard: return
        l_res = self.cbox_resolution.cbox.itemText(i_idx).split(" x ")
        oc_vf_settings = self.oc_camera.viewfinderSettings()
        if oc_vf_settings.isNull():
            self.fatal_error("Unable to retrieve camera settings")
        i_w, i_h = int(l_res[0]), int(l_res[1])
        oc_vf_settings.setResolution(i_w, i_h)
        self.oc_camera.setViewfinderSettings(oc_vf_settings)
        self.oc_view_finder.setFixedSize(i_w, i_h)
        if i_w >= self._MIN_WIN_WIDTH:
            self.adjustSize()
            self.setFixedSize(self.sizeHint())

    def __cb_on_frame_rate_cbox_index_changed(self, i_idx):
        if self.oc_camera is None:
            self.fatal_error("Unallocated camera object detected")
        if self.b_guard: return
        f_res = float(self.cbox_frame_rate.cbox.itemText(i_idx))
        oc_vf_settings = self.oc_camera.viewfinderSettings()
        if oc_vf_settings.isNull():
            self.fatal_error("Unable to retrieve camera settings")
        oc_vf_settings.setMinimumFrameRate(f_res)
        oc_vf_settings.setMaximumFrameRate(f_res)
        self.oc_camera.setViewfinderSettings(oc_vf_settings)

    def __camera_sync_start(self):
        i_sec_cnt = 0
        self.oc_camera.start()
        while True:
            cam_status = self.oc_camera.status()
            if cam_status == QCamera.ActiveStatus: break
            else:
                time.sleep(1)
                i_sec_cnt += 1
                if i_sec_cnt >= 10: self.fatal_error("Unable to start the camera")

    def __update_UI(self):
        # retrieve all supported resolutions and populate the resolution combo box
        l_resolutions = self.oc_camera.supportedViewfinderResolutions()
        if len(l_resolutions) > 0:
            l_res = []
            for oc_res in l_resolutions:
                l_res.append("%i x %i" % (oc_res.width(), oc_res.height()))
            self.cbox_resolution.cbox.clear()
            self.cbox_resolution.cbox.addItems(l_res)

        oc_vf_settings = self.oc_camera.viewfinderSettings()
        if oc_vf_settings.isNull():
            self.fatal_error("Unable to retrieve camera settings")

        # set current item index in the resolution combo box
        # according to the current resolution of our camera
        oc_curr_res = oc_vf_settings.resolution()
        s_res_hash = "%i x %i" % (oc_curr_res.width(), oc_curr_res.height())
        for i_idx in range(self.cbox_resolution.cbox.count()):
            if self.cbox_resolution.cbox.itemText(i_idx) == s_res_hash:
                self.cbox_resolution.cbox.setCurrentIndex(i_idx)

        # retrieve all supported frame rates and populate the frame rate combo box
        l_frates = self.oc_camera.supportedViewfinderFrameRateRanges()
        if len(l_frates) > 0:
            l_res = []
            for oc_frate in l_frates:
                l_res.append("%f" % oc_frate.minimumFrameRate)
            self.cbox_frame_rate.cbox.clear()
            self.cbox_frame_rate.cbox.addItems(l_res)

        # set current item index in the frame rate combo box
        # according to the current frame rate of our camera
        i_curr_frate = int(oc_vf_settings.minimumFrameRate())
        for i_idx in range(self.cbox_frame_rate.cbox.count()):
            if int(float(self.cbox_frame_rate.cbox.itemText(i_idx))) == i_curr_frate:
                self.cbox_frame_rate.cbox.setCurrentIndex(i_idx)

    def fatal_error(self, s_msg):
        if self.oc_camera is not None: self.oc_camera.stop()
        QtWidgets.QMessageBox.critical(None, "Fatal Error", "%s\nThe application will exit now." % s_msg)
        sys.exit(-1)

    def start_preview(self, oc_camera_info, oc_frame_cap_thread):
        if self.oc_camera is not None:
            self.fatal_error("Preallocated camera object detected")

        self.oc_camera_info = oc_camera_info
        self.oc_camera = QCamera(self.oc_camera_info)

        self.oc_camera.setViewfinder(self.oc_view_finder)
        self.oc_camera.setCaptureMode(QCamera.CaptureVideo)
        self.oc_camera.error.connect(lambda: self.show_error_message(self.oc_camera.errorString()))

        self.b_guard = True
        self.__camera_sync_start()
        self.__update_UI()
        self.b_guard = False

        self.setWindowTitle(self.oc_camera_info.description())
        self.adjustSize()
        self.setFixedSize(self.sizeHint())

    def stop_preview(self):
        if self.oc_camera is None:
            return # this is correct logic, no error here
        self.oc_camera.stop()
        self.oc_camera.unload()
        self.oc_camera = None
        self.oc_camera_info = None

    def is_save_state_needed(self):
        return False

    def save_state(self):
        pass

    def show_error_message(self, s_msg):
        err = QtWidgets.QErrorMessage(self)
        err.showMessage(s_msg)

    def closeEvent(self, event):
        if self.is_save_state_needed():
            self.save_state()
        self.stop_preview()
        self.closeSignal.emit()
Пример #3
0
    def __init__(self, d_param, oc_cam_info, *args, **kwargs):
        super(CSmartCameraPreviewWindow, self).__init__(d_param, *args, **kwargs)
        self.i_initial_cbox_resolution_idx = -1
        self.f_initial_frame_rate = d_param['initial_frame_rate'] # in Hz
        self.i_initial_frame_width = d_param['initial_frame_width']
        self.i_initial_frame_height = d_param['initial_frame_height']
        self.s_initial_frame_wh = "%i x %i" % (self.i_initial_frame_width, self.i_initial_frame_height)
        s_cam_descr = oc_cam_info.description()
        print("DEBUG: CSmartCameraPreviewWindow(): [%s @ %.1f Hz] %s" % \
             (self.s_initial_frame_wh, self.f_initial_frame_rate, s_cam_descr) \
        )

        oc_cam = QCamera(oc_cam_info)

        oc_cam.load()
        l_resolutions = oc_cam.supportedViewfinderResolutions()
        l_frate_ranges = oc_cam.supportedViewfinderFrameRateRanges()
        oc_cam.unload()

        del oc_cam

        if len(l_frate_ranges) == 0 or len(l_resolutions) == 0:
            raise RuntimeError("The camera (%s) does not support frame rate/resolution information retrieval" % s_cam_descr)

        b_requested_fsize_found = False
        for oc_res in l_resolutions:
            if self.s_initial_frame_wh == "%i x %i" % (oc_res.width(), oc_res.height()):
                b_requested_fsize_found = True
                break

        if not b_requested_fsize_found:
            raise RuntimeError( \
                "The camera [%s] does not support frame size value [%s] requested in the ini file" % \
                (s_cam_descr, self.s_initial_frame_wh) \
            )

        b_requested_frate_found = False
        for oc_frate in l_frate_ranges:
            if abs(oc_frate.minimumFrameRate - self.f_initial_frame_rate) <= 0.5:
                b_requested_frate_found = True

        if not b_requested_frate_found:
            raise RuntimeError( \
                "The camera [%s] does not support frame rate value [%i Hz] requested in the ini file" % \
                (s_cam_descr, self.f_initial_frame_rate) \
            )

        self.b_startup_guard = False
        self.toolbar = QtWidgets.QToolBar("Preview")

        l_items = []
        for oc_res in l_resolutions:
            l_items.append("%i x %i" % (oc_res.width(), oc_res.height()))
        self.cbox_resolution = CLabeledComboBox("Resolution:")
        self.cbox_resolution.cbox.addItems(l_items)
        self.cbox_resolution.cbox.currentIndexChanged.connect(self.__cb_on_resolution_cbox_index_changed)

        self.toolbar.addWidget(self.cbox_resolution)
        self.toolbar.addSeparator()

        l_items = []
        for oc_frate in l_frate_ranges:
            l_items.append("%f" % oc_frate.minimumFrameRate)
        self.cbox_frame_rate = CLabeledComboBox("Frame Rate:")
        self.cbox_frame_rate.cbox.addItems(l_items)
        self.cbox_frame_rate.cbox.currentIndexChanged.connect(self.__cb_on_frame_rate_cbox_index_changed)

        self.toolbar.addWidget(self.cbox_frame_rate)
        self.toolbar.addSeparator()
        self.addToolBar(self.toolbar)
Пример #4
0
class CMainWindow(QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(CMainWindow, self).__init__(*args, **kwargs)
        self.oc_camera = None
        self.l_cameras = QCameraInfo.availableCameras()
        if len(self.l_cameras) == 0:
            self.fatal_error("No cameras found!")

        # Top tool-bar
        self.oc_toolbar = QtWidgets.QToolBar("Video source selector")
        self.oc_toolbar.setMovable(False)

        lbl = QtWidgets.QLabel("Select video source:")
        self.oc_toolbar.addWidget(lbl)

        camera_selector = QtWidgets.QComboBox()
        camera_selector.addItems([ "[ %i ] %s" % (i_idx, oc_cam.description()) for i_idx, oc_cam in enumerate(self.l_cameras)])
        camera_selector.currentIndexChanged.connect( self.start_preview )

        self.oc_toolbar.addWidget(camera_selector)
        self.oc_toolbar.layout().setSpacing(5)
        self.oc_toolbar.layout().setContentsMargins(5, 5, 5, 5)
        self.addToolBar(self.oc_toolbar)

        # Central part (video frame)
        self.oc_viewfinder = QCameraViewfinder()
        self.setCentralWidget(self.oc_viewfinder)

        # Bottom status bar
        self.status = QtWidgets.QStatusBar()
        self.setStatusBar(self.status)

        self.setWindowTitle("CamView")
        self.start_preview(0)

    def fatal_error(self, s_msg):
        QtWidgets.QMessageBox.critical(None, "Fatal Error", "%s\nThe application will exit now." % s_msg)
        sys.exit(-1)

    def start_preview(self, i_cam_idx):
        if self.oc_camera is not None:
            self.oc_camera.stop()
            del self.oc_camera
        self.oc_camera = QCamera(self.l_cameras[i_cam_idx])
        self.oc_camera.setViewfinder(self.oc_viewfinder)
        self.oc_camera.setCaptureMode(QCamera.CaptureVideo)
        self.oc_camera.error.connect(lambda: self.show_error(self.oc_camera.errorString()))
        self.oc_camera.start()

    def stop_preview(self):
        if self.oc_camera is None:
            return # this is correct logic, no error here
        self.oc_camera.stop()
        self.oc_camera.unload()
        self.oc_camera = None

    def show_error(self, s):
        err = QtWidgets.QErrorMessage(self)
        err.showMessage(s)

    def closeEvent(self, event):
        self.stop_preview()