Пример #1
0
class CameraMainWin(QtWidgets.QMainWindow, CameraWin.CameraWin):
    def __init__(self):
        super(CameraMainWin, self).__init__()
        self.setupUi(self)
        #定义相机实例对象并设置捕获模式
        self.camera = QCamera()
        self.camera.setCaptureMode(QCamera.CaptureViewfinder)
        self.cameraOpened = False  # 设置相机打开状态为未打开
        #设置取景器分辨率
        viewFinderSettings = QCameraViewfinderSettings()
        viewFinderSettings.setResolution(800, 600)
        self.camera.setViewfinderSettings(viewFinderSettings)
        #初始化取景器
        self.viewCamera = QtMultimediaWidgets.QCameraViewfinder(self)
        self.camera.setViewfinder(self.viewCamera)
        self.camera.setCaptureMode(QCamera.CaptureStillImage)
        self.camerLayout.addWidget(self.viewCamera)  #取景器放置到预留的布局中
        #设置图像捕获
        self.capture = QCameraImageCapture(self.camera)
        self.capture.setCaptureDestination(
            QCameraImageCapture.CaptureToBuffer)  #CaptureToBuffer
        self.switchCamera: QPushButton
        self.switchCamera.clicked.connect(self.SwitchCamera)
        self.takePic.clicked.connect(self.TakePic)
        self.capture.error.connect(lambda i, e, s: self.alert(s))
        self.capture.imageAvailable.connect(self.saveImage)
        self.capture.imageCaptured.connect(
            lambda d, i: self.status.showMessage("Image %04d captured" % self.
                                                 save_seq))

    #相机(摄像头)开关处理
    def SwitchCamera(self):
        if not self.cameraOpened:
            print('test1')
            self.camera.start()
            print('test2')
            self.cameraOpened = True
            self.switchCamera.setText("关闭摄像头")
        else:
            self.camera.stop()
            self.cameraOpened = False
            self.switchCamera.setText("打开摄像头")

    def TakePic(self):  #拍照响应槽函数,照片保存到文件
        FName = fr"/Users/xiaozhenlong/Desktop/tmp/{time.strftime('%Y%m%d%H%M%S', time.localtime())}"  #文件名初始化
        print(self.capture.capture(FName + '.jpg'))
        print(f"捕获图像保存到文件:{FName}.jpg")

    def saveImage(self, requestId, image):
        print('test3')
        image: PyQt5.QtMultimedia.QVideoFrame
        image = qimage2numpy2(image.image())
        print(image.shape)
        cv2.imwrite('/Users/xiaozhenlong/Desktop/tmp/test3.jpg', image)
class CameraMainWin(QtWidgets.QMainWindow, CameraWin.Ui_CameraWin):
    def __init__(self):
        super(CameraMainWin, self).__init__()
        self.setupUi(self)
        #定义相机实例对象并设置捕获模式
        self.camera = QCamera()
        self.camera.setCaptureMode(QCamera.CaptureViewfinder)
        self.cameraOpened = False  # 设置相机打开状态为未打开
        #设置取景器分辨率
        viewFinderSettings = QCameraViewfinderSettings()
        viewFinderSettings.setResolution(800, 600)
        self.camera.setViewfinderSettings(viewFinderSettings)
        #初始化取景器
        self.viewCamera = QtMultimediaWidgets.QCameraViewfinder(self)
        self.camera.setViewfinder(self.viewCamera)
        self.camerLayout.addWidget(self.viewCamera)  #取景器放置到预留的布局中
        #设置图像捕获
        self.capImg = QCameraImageCapture(self.camera)
        self.capImg.setCaptureDestination(
            QCameraImageCapture.CaptureToFile)  #CaptureToBuffer

    #相机(摄像头)开关处理
    def switchCamera(self):
        if not self.cameraOpened:
            self.camera.start()
            self.cameraOpened = True
            self.btnSwitchCamera.setText("关闭摄像头")
        else:
            self.camera.stop()
            self.cameraOpened = False
            self.btnSwitchCamera.setText("打开摄像头")

    def takePic(self):  #拍照响应槽函数,照片保存到文件
        FName = fr"E:\iddatabasepic\cap{time.strftime('%Y%m%d%H%M%S', time.localtime())}"  #文件名初始化
        self.capImg.capture(FName)
        print(f"捕获图像保存到文件:{FName}.jpg")
Пример #3
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
Пример #4
0
class mainInterface(QWidget):

    # 定义信号
    processFinished = pyqtSignal(dict)

    def __init__(self):
        """
        初始化
        :return: null
        """
        # 超类初始化
        super().__init__()

        # UI初始化
        self.ui = Ui_mainWidget()
        self.ui.setupUi(self)
        self.grabKeyboard()
        self.setMouseTracking(True)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowIcon(QIcon('OCR.ico'))

        # 初始化相机
        self.camera = QCamera()
        self.imageCapture = QCameraImageCapture(self.camera)
        self.viewsetting = QCameraViewfinderSettings()
        self.initimplement()

        # 初始化标题栏
        self.initTitleBar()

        # 初始化系统托盘
        self.tray = QSystemTrayIcon()
        self.tray.setIcon(QIcon('OCR.ico'))
        self.initTray()

        # OCR识别部分
        self.OCR = ocr()
        self.OCR.setappid('1257206643')
        self.OCR.setsecretid('AKIDFTddWEg9Ncsz0sE7oOpBNOExdDdeCUJ3')
        self.OCR.setsecretkey('FQitsgUND8yfrZK0RrBMOJB5tWhCm5Ol')

        # 初始化登录部分
        self.logWidget = QWidget()
        self.logui = Ui_Form()
        self.logui.setupUi(self.logWidget)
        self.logWidget.setWindowFlags(Qt.FramelessWindowHint)
        self.logWidget.setWindowModality(Qt.ApplicationModal)
        self.logui.close_btn.clicked.connect(self.logWidget.close)

        # 初始化变量
        self.mousePressd = False
        self.mousePoint = None
        self.result = {}
        self.isFirst = False
        self.ocrType = ocrType.ocr_general  # 默认为印刷体识别

        # 初始化字定义信号连接
        self.processFinished.connect(self.updateOCRInfo)
        self.ui.btn_login.clicked.connect(self.logWidget.show)
        self.ui.comboBox_choose.currentIndexChanged.connect(self.changeocrType)

    def initTitleBar(self):
        """
        初始化标题栏
        :return: null
        """
        self.ui.frame.setStyleSheet(
            "QFrame#frame{background-color:rgb(244, 76, 76);}")
        self.ui.label_logo.setStyleSheet(
            "QLabel{border-image:url(./image/ocr.png);}")
        self.ui.label_title.setStyleSheet(
            "QLabel{border-image:url(./image/iOCR.png);}")
        self.ui.comboBox_choose.setStyleSheet(
            "QComboBox {border-radius:15px;border: 2px solid #4AFFF4;font-family:'楷体';font-size:20px;}"
            "QComboBox QAbstractItemView::item{height:50px;width:200px;}"
            "QComboBox::down-arrow{image: url(./image/arrow.png);width:25px;height:25px;}"
            "QComboBox::drop-down {subcontrol-origin: padding;subcontrol-position:top right;border:none;margin-right:30px;}"
            "QComboBox::down-arrow:hover{image:url(./image/arrow_hover.png);width:25px;height:25px;}"
            "QComboBox::down-arrow:on {top: 1px;left: 1px;}")
        self.ui.comboBox_choose.insertItem(0, '       印刷体识别')
        self.ui.comboBox_choose.insertItem(1, '       手写体识别')
        self.ui.comboBox_choose.insertItem(2, '       身份证识别')
        self.ui.comboBox_choose.insertItem(3, '       名片识别')
        self.ui.comboBox_choose.insertItem(4, '       银行卡识别')
        self.ui.btn_login.setStyleSheet(
            "QPushButton{border-image:url(./image/default-portrait.png);}")
        self.ui.btn_setting.setStyleSheet(
            "QPushButton{border-image:url(./image/settings.png);}"
            "QPushButton:hover{border-image:url(./image/qcconfig-hover.png);}")
        self.ui.btn_min.setStyleSheet(
            "QPushButton{border-image:url(./image/mini_new.png);}"
            "QPushButton:hover{border-image:url(./image/mini_hover_new.png);}")
        self.ui.btn_close.setStyleSheet(
            "QPushButton{border-image:url(./image/close.png);}"
            "QPushButton:hover{border-image:url(./image/close-hover.png);}")
        self.ui.checkBox_cam.setStyleSheet(
            "QCheckBox{spacing: 5px;font-size: 24px;vertical-align:middle}"
            "QCheckBox::indicator { width: 45px;height: 45px;}"
            "QCheckBox::indicator::unchecked {image: url(./image/close_cam.png);}"
            "QCheckBox::indicator::checked { image: url(./image/open_cam.png);}"
        )
        self.ui.captureBtn.setStyleSheet(
            "QPushButton{border-style: outset;border-width: 2px;border-color: rgb(82,215,100);border-radius: 5px;font-size: 24px;}"
            "QPushButton:pressed{background-color: rgb(176,215,181);border-style: inset;}"
        )

        self.ui.checkBox_cam.setChecked(True)

        self.ui.btn_close.clicked.connect(lambda: qApp.quit())
        self.ui.btn_min.clicked.connect(self.miniToTray)
        self.ui.checkBox_cam.stateChanged.connect(self.camControl)

    def initTray(self):
        """
        初始化系统托盘信息
        :return:
        """
        tray_menu = QMenu()
        restoreAction = QAction('&Show', self)
        quitAction = QAction('&Quit', self)
        tray_menu.addAction(restoreAction)
        tray_menu.addAction(quitAction)
        self.tray.setContextMenu(tray_menu)
        restoreAction.triggered.connect(self.trayActivatedEvent)
        quitAction.triggered.connect(qApp.quit)
        self.tray.activated.connect(self.trayActivatedEvent)

    def initimplement(self):
        """
        初始化实现端口
        :return: ui
        """
        camInfo = QCameraInfo(self.camera)
        if camInfo.defaultCamera().isNull():
            QMessageBox.warning(self, 'Warning', 'No available camera!',
                                QMessageBox.Ok)
            return -1
        else:
            self.ui.caputurePhoto.setText(camInfo.description())
            self.camera.setViewfinder(self.ui.cameraShow)
            self.camera.setCaptureMode(QCamera.CaptureStillImage)
            self.camera.load()
            resolution = self.camera.supportedViewfinderResolutions()
            if len(resolution) != 0:
                if QSize(640, 480) in resolution:
                    self.viewsetting.setResolution(QSize(640, 480))
                elif QSize(640, 360) in resolution:
                    self.viewsetting.setResolution(QSize(640, 360))
                else:
                    self.viewsetting.setResolution(resolution[0])
                self.camera.setViewfinderSettings(self.viewsetting)

            # ------------------------------Note--------------------------------
            # 此种方法利用摄像头准备捕捉图像的状态来进行捕捉图像,readyForCapture
            # 为true时,才进行捕捉图像,详见下面捕捉函数槽函数。这种方法将进行不
            # 停的捕捉,将每次捕捉的相邻图像进行图像相似度判断。当图像相似度低于
            # 阈值时,认定为新图像,才进行OCR识别。否则仅捕捉图像而不进行识别。当
            # 然捕捉图像速度过于太快时,可以用定时器,每隔0.5秒,去检查readyFor
            # Capture状态位,进而有效控制程序资源。
            # 本应用中采用按键捕捉方式,非自动,详见下面按键捕捉事件
            # ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
            # self.imageCapture.readyForCaptureChanged.connect(self.captureimage)

            self.camera.start()

        self.ui.caputurePhoto.setScaledContents(True)

        self.imageCapture.setCaptureDestination(
            QCameraImageCapture.CaptureToBuffer)

        self.imageCapture.imageCaptured.connect(self.displayimage)

        self.ui.captureBtn.clicked.connect(self.openDlg)

    def displayimage(self, num, image):
        """
        显示图形
        :param num: number
        :param image: image
        :return: null
        """
        self.ui.caputurePhoto.setPixmap(QPixmap.fromImage(image))
        self.ui.ocrInfo.setText('识别中......')
        t = threading.Thread(target=self.ocrForImage, args=(image, ))
        t.start()

    # def captureimage(self, state):
    #     """
    #     捕捉图像槽函数
    #     :state: 状态变量
    #     :return: null
    #     """
    #     if state is True:
    #         self.camera.searchAndLock()
    #         self.imageCapture.capture()
    #         self.camera.unlock()

    # def saveimage(self):
    #     """
    #     保存图像槽函数
    #     :return: null
    #     """
    #     pix = QPixmap(self.ui.caputurePhoto.pixmap())
    #     if pix:
    #         pix.save(r'D://1.png', 'PNG')
    #         QMessageBox.information(self, 'Message', 'Capture Successfully', QMessageBox.Ok)

    def ocrForImage(self, image):
        """
        为截取的图片进行ocr识别
        :param image: QImage
        :return: null
        """
        # Note:子线程里不能对ui界面做改动,ui界面修改只能在主线程中修改,下面注释的做法是错误的
        # self.ui.ocrInfo.setText('识别中......')
        byte = QByteArray()
        buffer = QBuffer(byte)
        buffer.open(QIODevice.WriteOnly)
        image.save(buffer, 'PNG')
        if self.ocrType == ocrType.ocr_general:
            self.result = self.OCR.client.general_detect(
                CIBuffers([byte.data()]))
        elif self.ocrType == ocrType.ocr_handwriting:
            self.result = self.OCR.client.handwriting_detect(
                CIBuffers([byte.data()]))
        elif self.ocrType == ocrType.ocr_idcard:
            self.result = self.OCR.client.idcard_detect(
                CIBuffers([byte.data()]), 0)
        elif self.ocrType == ocrType.ocr_namecard:
            self.result = self.OCR.client.namecard_detect(
                CIBuffers([byte.data()]), 0)
        elif self.ocrType == ocrType.ocr_bankcard:
            self.result = self.OCR.client.bankcard_detect(
                CIBuffers([byte.data()]))
        else:
            pass
        self.processFinished.emit(self.result)

    def updateOCRInfo(self, res):
        """
        将ocr识别结果显示在信息框中
        :param res:
        :return:
        """
        if self.ocrType == ocrType.ocr_general or self.ocrType == ocrType.ocr_handwriting:
            if res['code'] == 0 and res['message'] == 'OK':
                self.ui.ocrInfo.setText('OK')
                ocrInfo = []
                for i in range(len(self.result['data']['items'])):
                    ocrInfo.append(
                        self.result['data']['items'][i]['itemstring'])
                self.ui.ocrInfo.setText(''.join(ocrInfo))
            else:
                self.ui.ocrInfo.setText('识别失败!')
        elif self.ocrType == ocrType.ocr_bankcard:
            if res['code'] == 0 and res['message'] == 'OK':
                self.ui.ocrInfo.setText('OK')
                ocrInfo = []
                for i in range(len(self.result['data']['items'])):
                    ocrInfo.append(self.result['data']['items'][i]['item'])
                    ocrInfo.append(':')
                    ocrInfo.append(
                        self.result['data']['items'][i]['itemstring'])
                    ocrInfo.append('\n')
                self.ui.ocrInfo.setText(''.join(ocrInfo))
            else:
                self.ui.ocrInfo.setText('识别失败!')
        elif self.ocrType == ocrType.ocr_idcard:
            if res['result_list'][0]['code'] == 0 and res['result_list'][0][
                    'message'] == 'OK':
                self.ui.ocrInfo.setText('OK')
                ocrInfo = []
                ocrInfo_keys = list(
                    self.result['result_list'][0]['data'].keys())
                ocrInfo_values = list(
                    self.result['result_list'][0]['data'].values())
                for i in range(
                        len(self.result['result_list'][0]['data']) // 2):
                    ocrInfo.append(ocrInfo_keys[i])
                    ocrInfo.append(':')
                    ocrInfo.append(ocrInfo_values[i])
                    ocrInfo.append('\n')
                self.ui.ocrInfo.setText(''.join(ocrInfo))
            else:
                self.ui.ocrInfo.setText('识别失败!')
        elif self.ocrType == ocrType.ocr_namecard:
            if res['result_list'][0]['code'] == 0 and res['result_list'][0][
                    'message'] == 'OK':
                self.ui.ocrInfo.setText('OK')
                ocrInfo = []
                for i in range(len(self.result['result_list'][0]['data'])):
                    ocrInfo.append(
                        self.result['result_list'][0]['data'][i]['item'])
                    ocrInfo.append(':')
                    ocrInfo.append(
                        self.result['result_list'][0]['data'][i]['value'])
                    ocrInfo.append('\n')
                self.ui.ocrInfo.setText(''.join(ocrInfo))
            else:
                self.ui.ocrInfo.setText('识别失败!')
        else:
            pass

    def camControl(self, state):
        """
        槽函数
        控制相机开关
        :param state: checkbox开关状态
        :return:null
        """
        if state == Qt.Unchecked:
            self.ui.cameraShow.setUpdatesEnabled(False)
        elif state == Qt.Checked:
            self.ui.cameraShow.setUpdatesEnabled(True)
        else:
            return -1

    def miniToTray(self):
        """
        槽函数
        最小化到系统托盘
        :return:null
        """
        if not self.tray.isVisible():
            self.tray.show()
        if self.tray.isVisible():
            if self.isFirst is False:
                QMessageBox.information(
                    self, "Systray", "The program will keep running in the "
                    "system tray. To terminate the program, "
                    "choose <b>Quit</b> in the context menu "
                    "of the system tray entry.")
                self.isFirst = True
            self.hide()

    def trayActivatedEvent(self, reason):
        """
        槽函数
        响应点击托盘图标
        :param reason: 响应原因
        :return: null
        """
        if reason == QSystemTrayIcon.Context:
            pass
        else:
            self.tray.hide()
            self.show()

    def openDlg(self):
        """
        槽函数
        打开对话框选取文件
        :return:文件名
        """
        filename, filetype = QFileDialog.getOpenFileName(
            self, '选取图片', path.expanduser('~'),
            "Image Files (*.png *.jpg *.bmp)")
        if filename:
            if QFile(filename).size() >= 6291456:
                QMessageBox.information(self, '打开图片',
                                        '选择图片大于6MB大小,暂不支持识别,请重新选择。')
                self.openDlg()
            else:
                self.displayimage(0, QImage(filename))

    def keyPressEvent(self, e):
        """
        槽函数
        键盘按键响应事件
        :param e: 按键事件
        :return: null
        """
        if e.key() == Qt.Key_Space:
            if self.imageCapture.isReadyForCapture():
                self.camera.searchAndLock()
                self.imageCapture.capture()
                self.camera.unlock()

    def mouseMoveEvent(self, e):
        """
        槽函数
        定义鼠标移动事件
        :param e: QMouseEvent
        :return: null
        """
        if (e.buttons() == Qt.LeftButton) and self.mousePressd:
            self.move(e.globalPos() - self.mousePoint)
            e.accept()

    def mousePressEvent(self, e):
        """
        槽函数
        定义鼠标按下事件
        :param e: QMouseEvent
        :return: null
        """
        if e.button() == Qt.LeftButton:
            self.mousePressd = True
            self.mousePoint = e.globalPos() - self.pos()
            e.accept()

    def mouseReleaseEvent(self, e):
        """
        槽函数
        定义鼠标松开事件
        :param e: QMouseEvent
        :return: null
        """
        self.mousePressd = False

    def changeocrType(self, index):
        """
        槽函数
        改变ocr识别类型
        :param index: int
        :return: null
        """
        if index == 0:
            self.ocrType = ocrType.ocr_general
        elif index == 1:
            self.ocrType = ocrType.ocr_handwriting
        elif index == 2:
            self.ocrType = ocrType.ocr_idcard
        elif index == 3:
            self.ocrType = ocrType.ocr_namecard
        elif index == 4:
            self.ocrType = ocrType.ocr_bankcard
        else:
            pass
Пример #5
0
class CameraInterface(CameraBase.CameraBase):
    def __init__(self, *args, camera_info=None):
        super(CameraInterface, self).__init__(*args)
        # 定义相机实例对象并设置捕获模式
        if camera_info:
            self.mCamera = QCamera(camera_info)
        else:
            self.mCamera = QCamera()
        self.mCamera.setCaptureMode(QCamera.CaptureViewfinder)
        self.mDisplayWidth = 800
        self.mDisplayHeight = 600
        self.mRate = 10

        # 设置取景器分辨率
        self.setDisplaySize(self.mDisplayWidth, self.mDisplayHeight)

        self.setRate(self.mRate)

        # 初始化取景器
        self.mViewCamera = QtMultimediaWidgets.QCameraViewfinder(self)
        self.mViewCamera.show()
        self.mCamera.setViewfinder(self.mViewCamera)
        self.mCamera.setCaptureMode(QCamera.CaptureStillImage)

        # 设置图像捕获
        self.mCapture = QCameraImageCapture(self.mCamera)
        if self.mCapture.isCaptureDestinationSupported(
                QCameraImageCapture.CaptureToBuffer):
            self.mCapture.setCaptureDestination(
                QCameraImageCapture.CaptureToBuffer)  # CaptureToBuffer

        # self.mCapture.error.connect(lambda i, e, s: self.alert(s))
        self.mCapture.imageAvailable.connect(self.readFrame)

        self.mTimerImageGrab = QTimer(self)
        self.mTimerImageGrab.timeout.connect(self.timerImgGrab)
        # self.t1 = 0.0

    def timerImgGrab(self):
        self.mCapture.capture('tmp.jpg')

    def readFrame(self, requestId, image):
        self.mFrame = image.image().copy()

    def openCamera(self):
        if not self.mCameraOpened:
            self.mCamera.start()

            viewFinderSettings = QCameraViewfinderSettings()
            rate_range = self.mCamera.supportedViewfinderFrameRateRanges()
            if rate_range:
                viewFinderSettings.setMinimumFrameRate(
                    rate_range[0].minimumFrameRate)
                viewFinderSettings.setMaximumFrameRate(
                    rate_range[0].maximumFrameRate)
            else:
                viewFinderSettings.setMinimumFrameRate(1)
                viewFinderSettings.setMaximumFrameRate(self.mRate)
            self.mTimerImageGrab.start(1000 / self.mRate)
            self.mCameraOpened = True

    def releaseCamera(self):
        if self.mCameraOpened:
            self.mCamera.stop()
            self.mCameraOpened = False
            self.signalReleased.emit()

    def takePictures(self, path: str):
        self.mCapture.setCaptureDestination(QCameraImageCapture.CaptureToFile)
        self.mCapImg.capture(path)
        self.mCapture.setCaptureDestination(
            QCameraImageCapture.CaptureToBuffer)

    def takeVideo(self, path: str):
        pass

    def endTakeVideo(self):
        pass

    def setDisplaySize(self, display_width_: int, display_height_: int):
        self.mDisplayWidth = display_width_
        self.mDisplayHeight = display_height_
        viewFinderSettings = QCameraViewfinderSettings()
        viewFinderSettings.setResolution(self.mDisplayWidth,
                                         self.mDisplayHeight)
        self.mCamera.setViewfinderSettings(viewFinderSettings)

    def setRate(self, rate):
        self.mRate = rate