def take_photo(self, camera_save_path):
     image_capture = QCameraImageCapture(self.camera)
     save_path = str(Path(os.path.expanduser(camera_save_path)))
     photo_path = os.path.join(
         save_path, "EAF_Camera_Photo_" + time.strftime(
             "%Y-%m-%d_%H:%M:%S", time.localtime(int(time.time()))))
     image_capture.capture(photo_path)
     self.message_to_emacs.emit("Captured Photo at " + photo_path)
    def take_photo(self):
        photo_path = os.path.join(
            str(Path.home()), "EAF_Camera_Photo_" + time.strftime(
                "%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))))

        image_capture = QCameraImageCapture(self.camera)
        image_capture.capture(photo_path)

        self.message_to_emacs.emit("Save photo at: " + photo_path)
 def take_photo(self, camera_save_path):
     image_capture = QCameraImageCapture(self.camera)
     save_path = str(Path(os.path.expanduser(camera_save_path)))
     photo_path = os.path.join(
         save_path, "EAF_Camera_Photo_" +
         time.strftime("%Y%m%d_%H%M%S", time.localtime(int(time.time()))))
     return image_capture.capture(photo_path)
示例#4
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)
示例#5
0
    def onLogInClicked(self):
        capture = QCameraImageCapture(self.camera_obj)
        capture.capture(__file__[:-14:] + 'capture.jpg')

        sleep(1)

        s_data = {'image': open(__file__[:-14:] + 'capture.jpg', 'rb')}
        r = requests.post(self.veg_cfg.get_db_addr(), files=s_data)

        if r.json()['status'] != 'ok':
            QMessageBox.warning(
                self, 'Verification failed',
                'Failed to pass identity verification.\nTry again or cantact your admin (╯°^°)╯┻━┻',
                QMessageBox.Ok)
        else:
            if self.veg_cfg.get_browser() == 'firefox':
                fire = auth.FirefoxAuth(r.json()['login'], r.json()['passwd'])
                fire.get_auth_token()
            else:
                chrome = auth.ChromeAuth(r.json()['login'], r.json()['passwd'])
                chrome.get_auth_token()
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")
class Camera(QMainWindow):
    def __init__(self, parent=None):
        super(Camera, self).__init__(parent)

        self.ui = Ui_Camera()

        self.camera = None
        self.imageCapture = None
        # self.mediaRecorder = None
        self.isCapturingImage = False
        self.applicationExiting = False

        self.imageSettings = QImageEncoderSettings()
        self.audioSettings = QAudioEncoderSettings()
        # self.videoSettings = QVideoEncoderSettings()
        # self.videoContainerFormat = ''

        self.ui.setupUi(self)

        cameraDevice = QByteArray()

        videoDevicesGroup = QActionGroup(self)
        videoDevicesGroup.setExclusive(True)

        for deviceName in QCamera.availableDevices():
            description = QCamera.deviceDescription(deviceName)
            videoDeviceAction = QAction(description, videoDevicesGroup)
            videoDeviceAction.setCheckable(True)
            videoDeviceAction.setData(deviceName)

            if cameraDevice.isEmpty():
                cameraDevice = deviceName
                videoDeviceAction.setChecked(True)

            self.ui.menuDevices.addAction(videoDeviceAction)

        videoDevicesGroup.triggered.connect(self.updateCameraDevice)
        self.ui.captureWidget.currentChanged.connect(self.updateCaptureMode)

        #self.ui.lockButton.hide()

        self.setCamera(cameraDevice)

    def setCamera(self, cameraDevice):
        if cameraDevice.isEmpty():
            self.camera = QCamera()
        else:
            self.camera = QCamera(cameraDevice)

        self.camera.stateChanged.connect(self.updateCameraState)
        self.camera.error.connect(self.displayCameraError)

        # self.mediaRecorder = QMediaRecorder(self.camera)
        # self.mediaRecorder.stateChanged.connect(self.updateRecorderState)

        self.imageCapture = QCameraImageCapture(self.camera)

        # self.mediaRecorder.durationChanged.connect(self.updateRecordTime)
        # self.mediaRecorder.error.connect(self.displayRecorderError)

        # self.mediaRecorder.setMetaData(QMediaMetaData.Title, "Test Title")

        # self.ui.exposureCompensation.valueChanged.connect(
        #         self.setExposureCompensation)

        self.camera.setViewfinder(self.ui.viewfinder)

        self.updateCameraState(self.camera.state())
        # self.updateLockStatus(self.camera.lockStatus(), QCamera.UserRequest)
        # self.updateRecorderState(self.mediaRecorder.state())

        self.imageCapture.readyForCaptureChanged.connect(self.readyForCapture)
        self.imageCapture.imageCaptured.connect(self.processCapturedImage)
        self.imageCapture.imageSaved.connect(self.imageSaved)

        # self.camera.lockStatusChanged.connect(self.updateLockStatus)

        self.ui.captureWidget.setTabEnabled(
            0, self.camera.isCaptureModeSupported(QCamera.CaptureStillImage))
        self.ui.captureWidget.setTabEnabled(
            1, self.camera.isCaptureModeSupported(QCamera.CaptureVideo))

        self.updateCaptureMode()
        self.camera.start()

    def keyPressEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_CameraFocus:
            self.displayViewfinder()
            self.camera.searchAndLock()
            event.accept()
        elif event.key() == Qt.Key_Camera:
            if self.camera.captureMode() == QCamera.CaptureStillImage:
                self.takeImage()
            # elif self.mediaRecorder.state() == QMediaRecorder.RecordingState:
            #     self.stop()
            # else:
            #     self.record()

            event.accept()
        else:
            super(Camera, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_CameraFocus:
            self.camera.unlock()
        else:
            super(Camera, self).keyReleaseEvent(event)

    # def updateRecordTime(self):
    #     msg = "Recorded %d sec" % (self.mediaRecorder.duration() // 1000)
    #     self.ui.statusbar.showMessage(msg)

    def processCapturedImage(self, requestId, img):
        scaledImage = img.scaled(self.ui.viewfinder.size(), Qt.KeepAspectRatio,
                                 Qt.SmoothTransformation)

        self.ui.lastImagePreviewLabel.setPixmap(QPixmap.fromImage(scaledImage))

        self.displayCapturedImage()
        QTimer.singleShot(4000, self.displayViewfinder)

    def configureCaptureSettings(self):
        if self.camera.captureMode() == QCamera.CaptureStillImage:
            self.configureImageSettings()
        elif self.camera.captureMode() == QCamera.CaptureVideo:
            self.configureVideoSettings()

    # def configureVideoSettings(self):
    #     settingsDialog = VideoSettings(self.mediaRecorder)

    #     settingsDialog.setAudioSettings(self.audioSettings)
    #     settingsDialog.setVideoSettings(self.videoSettings)
    #     settingsDialog.setFormat(self.videoContainerFormat)

    #     if settingsDialog.exec_():
    #         self.audioSettings = settingsDialog.audioSettings()
    #         self.videoSettings = settingsDialog.videoSettings()
    #         self.videoContainerFormat = settingsDialog.format()

    #         self.mediaRecorder.setEncodingSettings(self.audioSettings,
    #                 self.videoSettings, self.videoContainerFormat)
    def configureOpenExcels(self):
        settingsopenexcelDialog = OpenExcels()
        settingsopenexcelDialog.initUI()

    def configureImageSettings(self):
        settingsDialog = ImageSettings(self.imageCapture)

        settingsDialog.setImageSettings(self.imageSettings)

        if settingsDialog.exec_():
            self.imageSettings = settingsDialog.imageSettings()
            self.imageCapture.setEncodingSettings(self.imageSettings)

    # def record(self):
    #     self.mediaRecorder.record()
    #     self.updateRecordTime()

    # def pause(self):
    #     self.mediaRecorder.pause()

    # def stop(self):
    #     self.mediaRecorder.stop()

    # def setMuted(self, muted):
    #     self.mediaRecorder.setMuted(muted)

    def toggleLock(self):
        if self.camera.lockStatus() in (QCamera.Searching, QCamera.Locked):
            self.camera.unlock()
        elif self.camera.lockStatus() == QCamera.Unlocked:
            self.camera.searchAndLock()

    # def updateLockStatus(self, status, reason):
    #     indicationColor = Qt.black

    #     if status == QCamera.Searching:
    #         self.ui.statusbar.showMessage("Focusing...")
    #         self.ui.lockButton.setText("Focusing...")
    #         indicationColor = Qt.yellow
    #     elif status == QCamera.Locked:
    #         self.ui.lockButton.setText("Unlock")
    #         self.ui.statusbar.showMessage("Focused", 2000)
    #         indicationColor = Qt.darkGreen
    #     # elif status == QCamera.Unlocked:
    #     #     self.ui.lockButton.setText("Focus")

    #         if reason == QCamera.LockFailed:
    #             self.ui.statusbar.showMessage("Focus Failed", 2000)
    #             indicationColor = Qt.red

    #     palette = self.ui.lockButton.palette()
    #     palette.setColor(QPalette.ButtonText, indicationColor)
    #     self.ui.lockButton.setPalette(palette)
    def display_absences(self, absences):
        self.ui.absenceNumber.display(absences)

    def takeImage(self):
        self.isCapturingImage = True
        self.imageCapture.capture()

    def startCamera(self):
        self.camera.start()

    def stopCamera(self):
        self.camera.stop()

    def updateCaptureMode(self):
        tabIndex = self.ui.captureWidget.currentIndex()
        captureMode = QCamera.CaptureStillImage if tabIndex == 0 else QCamera.CaptureVideo

        if self.camera.isCaptureModeSupported(captureMode):
            self.camera.setCaptureMode(captureMode)

    def updateCameraState(self, state):
        if state == QCamera.ActiveState:
            self.ui.actionStartCamera.setEnabled(False)
            self.ui.actionStopCamera.setEnabled(True)
            self.ui.captureWidget.setEnabled(True)
            self.ui.actionSettings.setEnabled(True)
        elif state in (QCamera.UnloadedState, QCamera.LoadedState):
            self.ui.actionStartCamera.setEnabled(True)
            self.ui.actionStopCamera.setEnabled(False)
            self.ui.captureWidget.setEnabled(False)
            self.ui.actionSettings.setEnabled(False)

    # def updateRecorderState(self, state):
    #     if state == QMediaRecorder.StoppedState:
    #         # self.ui.recordButton.setEnabled(True)
    #         self.ui.pauseButton.setEnabled(True)
    #         self.ui.stopButton.setEnabled(False)
    #     elif state == QMediaRecorder.PausedState:
    #         self.ui.recordButton.setEnabled(True)
    #         self.ui.pauseButton.setEnabled(False)
    #         self.ui.stopButton.setEnabled(True)
    #     elif state == QMediaRecorder.RecordingState:
    #         self.ui.recordButton.setEnabled(False)
    #         self.ui.pauseButton.setEnabled(True)
    #         self.ui.stopButton.setEnabled(True)

    def setExposureCompensation(self, index):
        self.camera.exposure().setExposureCompensation(index * 0.5)

    # def displayRecorderError(self):
    #     QMessageBox.warning(self, "Capture error",
    #             self.mediaRecorder.errorString())

    def displayCameraError(self):
        QMessageBox.warning(self, "Camera error", self.camera.errorString())

    def updateCameraDevice(self, action):
        self.setCamera(action.data())

    def displayViewfinder(self):
        self.ui.stackedWidget.setCurrentIndex(0)

    def displayCapturedImage(self):
        self.ui.stackedWidget.setCurrentIndex(1)

    def readyForCapture(self, ready):
        self.ui.takeImageButton.setEnabled(ready)

    def imageSaved(self, id, fileName):
        self.isCapturingImage = False

        if self.applicationExiting:
            self.close()

    def closeEvent(self, event):
        if self.isCapturingImage:
            self.setEnabled(False)
            self.applicationExiting = True
            event.ignore()
        else:
            event.accept()
示例#8
0
class Window(QWidget):

    # конструктор формы
    def __init__(self):
        super().__init__()
        self._Client = Biometric_Client(
            url='https://expasoft.com',
            port=2133,
            subscription_key='9fc9474b4bd16b492276eee41763a3cb')

        self.resize(800, 600)
        self.setObjectName("FormMain")
        self.setWindowTitle("БиоСКУД Archivist")

        self.labelHumans = QtWidgets.QLabel(self)
        self.labelHumans.setObjectName("labelHumans")
        self.labelHumans.setText("Профили сотрудников")
        self.labelHumans.setGeometry(QtCore.QRect(80, 15, 181, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.labelHumans.setFont(font)

        self.labelPhotos = QtWidgets.QLabel(self)
        self.labelPhotos.setObjectName("labelPhotos")
        self.labelPhotos.setText("Фото сотрудника")
        self.labelPhotos.setGeometry(QtCore.QRect(390, 15, 181, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.labelPhotos.setFont(font)

        self.listViewHumans = QtWidgets.QListWidget(self)
        self.listViewHumans.setObjectName("listViewHumans")
        self.listViewHumans.setGeometry(QtCore.QRect(10, 50, 291, 531))
        self.listViewHumans.setIconSize(QtCore.QSize(200, 200))
        self.listViewHumans.itemClicked.connect(self.LoadProfile)

        self.listViewPhotos = QtWidgets.QListWidget(self)
        self.listViewPhotos.setObjectName("listViewPhotos")
        self.listViewPhotos.setGeometry(QtCore.QRect(310, 50, 291, 281))
        self.listViewPhotos.setIconSize(QtCore.QSize(150, 150))

        self.labelName = QLabel(self)
        self.labelName.setText("ФИО:")
        self.labelName.move(310, 355)

        self.lineName = QLineEdit(self)
        self.lineName.resize(140, 25)
        self.lineName.move(350, 350)

        self.labelTag = QLabel(self)
        self.labelTag.setText("Пост:")
        self.labelTag.move(310, 385)

        self.lineTag = QLineEdit(self)
        self.lineTag.resize(140, 25)
        self.lineTag.move(350, 380)

        self.pushButtonAddProfile = QtWidgets.QPushButton(self)
        self.pushButtonAddProfile.setGeometry(QtCore.QRect(310, 420, 181, 51))
        self.pushButtonAddProfile.setObjectName("pushButtonAddProfile")
        self.pushButtonAddProfile.setText("Добавить профиль")
        self.pushButtonAddProfile.clicked.connect(self.AddProfile)

        self.pushButtonUpdateProfile = QtWidgets.QPushButton(self)
        self.pushButtonUpdateProfile.setGeometry(
            QtCore.QRect(310, 475, 181, 51))
        self.pushButtonUpdateProfile.setObjectName("pushButtonAddProfile")
        self.pushButtonUpdateProfile.setText("Обновить профиль")
        self.pushButtonUpdateProfile.clicked.connect(self.UpdateProfile)

        self.pushButtonDelProfile = QtWidgets.QPushButton(self)
        self.pushButtonDelProfile.setGeometry(QtCore.QRect(310, 530, 181, 51))
        self.pushButtonDelProfile.setObjectName("pushButtonDelProfile")
        self.pushButtonDelProfile.setText("Удалить профиль")
        self.pushButtonDelProfile.clicked.connect(self.DelProfile)

        self.CameraStream = QVideoWidget(self)
        self.CameraStream.setObjectName("videoCameraStream")
        self.CameraStream.setGeometry(QtCore.QRect(610, 25, 180, 200))

        self.device = QCamera.availableDevices()[0]
        self.camera = QCamera(self.device)
        self.camera.setViewfinder(self.CameraStream)
        self.camera.setCaptureMode(QCamera.CaptureStillImage)
        self.imageCapture = QCameraImageCapture(self.camera)
        self.imageCapture.imageSaved.connect(self.AddPhotoEnd)
        self.camera.start()

        self.pushButtonAddPhoto = QtWidgets.QPushButton(self)
        self.pushButtonAddPhoto.setObjectName("pushButtonAddPhoto")
        self.pushButtonAddPhoto.setText("Добавить фото")
        self.pushButtonAddPhoto.setGeometry(QtCore.QRect(610, 225, 181, 51))
        self.pushButtonAddPhoto.clicked.connect(self.AddPhotoBegin)

        self.pushButtonDelPhoto = QtWidgets.QPushButton(self)
        self.pushButtonDelPhoto.setObjectName("pushButtonDelPhoto")
        self.pushButtonDelPhoto.setText("Удалить фото")
        self.pushButtonDelPhoto.setGeometry(QtCore.QRect(610, 280, 181, 51))
        self.pushButtonDelPhoto.clicked.connect(self.DelPhoto)

        self.LoadProfiles()

# загружаем список сотрудников

    def LoadProfiles(self):
        self.listViewHumans.clear()
        AllProfiles = self._Client.get_profiles_ids()['result']
        if len(AllProfiles) != 0:
            for profile in AllProfiles:
                item = QtWidgets.QListWidgetItem()
                #item.setText(str(profile))
                if (GetInfo(str(profile)) != None):
                    item.setText(GetInfo(str(profile))["name"])
                item.setToolTip(str(profile))

                AllPhoto = self._Client.get_profile_images_ids(
                    profile)['result']
                if len(AllPhoto) != 0:
                    FileName = "img/" + str(profile) + '-' + str(
                        AllPhoto[0]) + '.jpg'
                    self._Client.get_profile_image(profile, AllPhoto[0],
                                                   FileName)
                    item.setIcon(QtGui.QIcon(FileName))
                self.listViewHumans.addItem(item)

    # загружаем профиль
    def LoadProfile(self, item):
        self.listViewPhotos.clear()
        #idProfile = int(item.text())
        idProfile = int(item.toolTip())
        AllPhoto = self._Client.get_profile_images_ids(idProfile)['result']
        for photo in AllPhoto:
            FileName = "img/" + str(idProfile) + '-' + str(photo) + '.jpg'
            self._Client.get_profile_image(idProfile, photo, FileName)

            item = QtWidgets.QListWidgetItem()
            item.setText(str(photo))
            item.setIcon(QtGui.QIcon(FileName))
            self.listViewPhotos.addItem(item)
        infoProfile = JsonDataBase.GetInfo(idProfile)
        if infoProfile != None:
            self.lineName.setText(infoProfile['name'])
            self.lineTag.setText(infoProfile['tag'])
        else:
            self.lineName.setText("")
            self.lineTag.setText("")

    # добавляем профиль
    def AddProfile(self):
        profile_name = self.lineName.text()
        profile_post = self.lineTag.text()
        Id_Profile = self._Client.add_profile(profile_name,
                                              '01.01.1111',
                                              'm',
                                              tags="").pop('result')
        JsonDataBase.AddInfo(Id_Profile, profile_name, '01.01.1111', "m",
                             profile_post)
        self.LoadProfiles()

    # обновляем профиль
    def UpdateProfile(self):
        Id_Profile = self.listViewHumans.currentItem().toolTip()
        profile_name = self.lineName.text()
        profile_post = self.lineTag.text()
        if (JsonDataBase.GetInfo(Id_Profile) != None):
            JsonDataBase.UpdateInfo(Id_Profile,
                                    name=profile_name,
                                    tag=profile_post)
        else:
            JsonDataBase.AddInfo(Id_Profile,
                                 name=profile_name,
                                 tag=profile_post)
        self.LoadProfiles()

    # удаляем профиль
    def DelProfile(self):
        Id_Profile = self.listViewHumans.currentItem().toolTip()
        self._Client.delete_profile(Id_Profile)
        JsonDataBase.DelInfo(Id_Profile)
        self.LoadProfiles()

    # добавляем фото
    def AddPhotoBegin(self):
        if self.imageCapture.isReadyForCapture():
            imgName = os.getcwd() + "\img\currentPhoto.jpg"
            self.camera.searchAndLock()
            self.imageCapture.capture(imgName)
            self.camera.unlock()

    def AddPhotoEnd(self):
        print(0)
        imgName = os.getcwd() + "\img\currentPhoto.jpg"
        imgName0 = os.getcwd() + "\img\currentPhoto0.jpg"
        idProfile = int(self.listViewHumans.currentItem().toolTip())
        self._Client.get_aligned_faces(imgName, "img\currentPhoto")
        self._Client.enroll_profile_face(idProfile, imgName0)
        self.LoadProfile(self.listViewHumans.currentItem())

    # удаляем фото
    def DelPhoto(self):
        #Id_Profile = self.listViewHumans.currentItem().text()
        Id_Profile = self.listViewHumans.currentItem().toolTip()
        Id_Photo = self.listViewPhotos.currentItem().text()
        self._Client.delete_image(Id_Profile, Id_Photo)
        self.LoadProfile(self.listViewHumans.currentItem())
示例#9
0
class MainWindow(QWidget):
    face = Face()

    def __init__(self):
        super().__init__()
        self.start_ui()

    def start_ui(self):
        self.zui = Ui_zwin()
        self.zui.setupUi(self)
        self.zui.camera_label.setScaledContents(True)

        # 初始化信息
        self.zui.label_xuehao.setText("工号:")
        self.zui.label_mingzi.setText("姓名:")
        self.zui.label_time.setText("签到时间:")

        # 查询按钮
        self.zui.cxbtn.clicked.connect(self.cx_ui)
        # 注册按钮
        self.zui.zcbtn.clicked.connect(self.zq_zc)
        # 签到按钮
        self.zui.qdbtn.clicked.connect(self.zq_qd)
        # 删除按钮
        self.zui.del_btn.clicked.connect(self.del_yg)
        # 导出按钮
        self.zui.out_btn.clicked.connect(self.out_ex)

        # 摄像头控制
        camera = QCamera(self)  # 创建摄像头
        cameraviewfinder = QCameraViewfinder(self.zui.camera_label)  # 创建显示窗口
        cameraviewfinder.resize(752, 420)
        self.cameraImageCapture = QCameraImageCapture(camera)  # 绑定获取的摄像头
        self.cameraImageCapture.setCaptureDestination(
            QCameraImageCapture.CaptureToFile)  # 获取数据类型
        camera.setCaptureMode(QCamera.CaptureStillImage)
        camera.setViewfinder(cameraviewfinder)  # 绑定窗口
        camera.start()  # 开启摄像头

    def out_ex(self):
        """
        导出考勤记录
        :return:
        """
        wk = Workbook()
        wb = wk.active
        wb.append(['姓名', '工号', '打卡时间', '状态'])
        result = obj.get_list("select name, no, ctime, st from qds", [])
        for i in result:
            wb.append(i)
        wk.save(r'kaoqing.xlsx')
        return QMessageBox.information(self, "提示", '导出成功...', QMessageBox.Yes,
                                       QMessageBox.Yes)

    def del_yg(self):
        """
        删除员工
        :return:
        """
        gh = self.zui.gonghao.text()
        if not gh:
            return QMessageBox.information(self, "提示", '请填写工号...',
                                           QMessageBox.Yes, QMessageBox.Yes)
        if obj.get_list('select no from user where no=%s', [
                gh,
        ]):
            obj.modify('delete from user where no=%s', [
                gh,
            ])
            return QMessageBox.information(self, "提示", '删除成功...',
                                           QMessageBox.Yes, QMessageBox.Yes)
        else:
            return QMessageBox.information(self, "提示", '删除失败...',
                                           QMessageBox.Yes, QMessageBox.Yes)

    def zc(self, xx, image):
        """
        注册
        :return:
        """
        self.cameraImageCapture.disconnect()
        pximap = QPixmap.fromImage(image)  # 获取摄像头图片
        pximap.save('image.jpg')  # 保存图片

        name = self.zui.mingzi.text()
        no = self.zui.xuehao.text()

        if not name or not no:
            QMessageBox.information(self, "提示", '请填写工号跟姓名...', QMessageBox.Yes,
                                    QMessageBox.Yes)
            return self.zui.zcbtn.setDisabled(False)

        path = 'image.jpg'
        print(103)
        face_token = self.face.C_addFace(name, no, path)
        print(105, face_token)

        if face_token:
            try:
                obj.modify(
                    "insert into user(name,no,face_token) values (%s,%s,%s)", [
                        name,
                        no,
                        face_token,
                    ])
            except Exception as e:
                obj.rollback()
                self.zui.zcbtn.setDisabled(False)
                return QMessageBox.information(self, "提示", '用户已存在...',
                                               QMessageBox.Yes,
                                               QMessageBox.Yes)
            QMessageBox.information(self, "提示", '注册成功...', QMessageBox.Yes,
                                    QMessageBox.Yes)
            obj.modify("insert into qds_month(name,no,st_no) values (%s,%s,0)",
                       [
                           name,
                           no,
                       ])
        else:
            QMessageBox.information(self, "提示", '注册失败...', QMessageBox.Yes,
                                    QMessageBox.Yes)
        self.zui.zcbtn.setDisabled(False)

    def qd(self, xx, image):
        """
        签到
        :return:
        """
        self.cameraImageCapture.disconnect()
        pximap = QPixmap.fromImage(image)  # 获取摄像头图片
        pximap.save('image.jpg')  # 保存图片

        t = self.face.C_searchFace('image.jpg')
        if t:
            no = t[1]
            name = t[0]
            face_token = t[2]

            res = obj.get_list("select no from user where face_token=%s", [
                face_token,
            ])
            if len(res) <= 0:
                QMessageBox.information(self, "提示", '数据库无此人信息...',
                                        QMessageBox.Yes, QMessageBox.Yes)
                return self.zui.qdbtn.setDisabled(False)
            ctime = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
            self.zui.label_xuehao.setText("工号:" + str(no))
            self.zui.label_mingzi.setText("姓名:" + str(name))
            self.zui.label_time.setText("签到时间:" + ctime)
            hour = datetime.datetime.today().hour
            st = '异常'
            if hour < 8 or hour > 17:
                st = '正常'
            # 执行sql语句
            obj.modify(
                "insert into qds(name,no,ctime,st) values (%s,%s,%s,%s)", [
                    name,
                    no,
                    ctime,
                    st,
                ])
            QMessageBox.information(self, "提示", '签到成功...', QMessageBox.Yes,
                                    QMessageBox.Yes)
        else:
            QMessageBox.information(self, "提示", '查无此人...', QMessageBox.Yes,
                                    QMessageBox.Yes)

        self.zui.qdbtn.setDisabled(False)

    def zq_zc(self):
        """注册抓取"""
        self.zui.zcbtn.setDisabled(True)
        self.cameraImageCapture.imageCaptured.connect(self.zc)  # 截取图片后链接显示方法
        self.cameraImageCapture.capture()  # 抓取方法

    def zq_qd(self):
        """签到抓取"""
        self.zui.qdbtn.setDisabled(True)
        self.cameraImageCapture.imageCaptured.connect(self.qd)  # 截取图片后链接显示方法
        self.cameraImageCapture.capture()  # 抓取方法

    def cx_ui(self):
        # 查询窗口
        self.cxui = Ui_cx()
        self.cxw = QDialog()
        self.cxui.setupUi(self.cxw)

        # 设置表格
        self.cxui.tableWidget.horizontalHeader().setStretchLastSection(False)
        self.cxui.tableWidget.setColumnWidth(0, 120)
        self.cxui.tableWidget.setColumnWidth(1, 120)
        # self.cxui.tableWidget.setColumnWidth(2, 100)
        self.cxui.tableWidget.horizontalHeader().setSectionResizeMode(
            0, QHeaderView.Stretch)
        self.cxui.tableWidget.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.Stretch)
        self.cxui.tableWidget.horizontalHeader().setSectionResizeMode(
            2, QHeaderView.Stretch)
        self.cxui.tableWidget.setRowCount(0)  # 设置行=0
        self.cxui.tableWidget.clearContents()  # 清除内容

        # 查询按钮
        self.cxui.btn_cx.disconnect()
        self.cxui.btn_cx.clicked.connect(self.cx)
        self.cxw.exec_()

    def cx(self):
        """查询数据"""
        self.cxui.tableWidget.setRowCount(0)  # 设置行=0
        self.cxui.tableWidget.clearContents()  # 清楚内容
        no = self.cxui.xuehao_cx.text()
        name = self.cxui.mingzi_cx.text()
        print(no, name, 'xxxxxx')
        if name == 'admin':
            data = obj.get_list(
                "select name, no, ctime, st_no from qds_month order by st_no desc",
                [])
            if len(data) <= 0:
                return QMessageBox.information(self, "提示", '查询无记录...',
                                               QMessageBox.Yes,
                                               QMessageBox.Yes)
            for k, i in enumerate(data):
                name = i[0]
                no = i[1]
                ctime = i[2]
                st = i[3]
                self.cxui.tableWidget.insertRow(k)
                self.cxui.tableWidget.setItem(k, 0, QTableWidgetItem(str(no)))
                self.cxui.tableWidget.item(k,
                                           0).setTextAlignment(Qt.AlignCenter)
                self.cxui.tableWidget.setItem(k, 1,
                                              QTableWidgetItem(str(name)))
                self.cxui.tableWidget.item(k,
                                           1).setTextAlignment(Qt.AlignCenter)
                self.cxui.tableWidget.setItem(k, 2,
                                              QTableWidgetItem(str(ctime)))
                self.cxui.tableWidget.item(k,
                                           2).setTextAlignment(Qt.AlignCenter)
                self.cxui.tableWidget.setItem(k, 3, QTableWidgetItem(str(st)))
                self.cxui.tableWidget.item(k,
                                           3).setTextAlignment(Qt.AlignCenter)
                print(i)
            return
        if not no and not name:
            time = datetime.datetime.now()
            sql = "select name, no, ctime, st from qds where st = '异常' " + 'order by ctime desc limit 7'
            print(sql)
            data = obj.get_list(sql, [])
            print(data)
            if len(data) <= 0:
                return QMessageBox.information(self, "提示", '查询无记录...',
                                               QMessageBox.Yes,
                                               QMessageBox.Yes)
            for k, i in enumerate(data):
                name = i[0]
                no = i[1]
                ctime = i[2]
                st = i[3]
                print(type(ctime))
                now = str(ctime)
                cur = str(time)
                now = now[:10]
                cur = cur[:10]
                if now != cur:
                    continue
                self.cxui.tableWidget.insertRow(k)
                self.cxui.tableWidget.setItem(k, 0, QTableWidgetItem(str(no)))
                self.cxui.tableWidget.item(k,
                                           0).setTextAlignment(Qt.AlignCenter)
                self.cxui.tableWidget.setItem(k, 1,
                                              QTableWidgetItem(str(name)))
                self.cxui.tableWidget.item(k,
                                           1).setTextAlignment(Qt.AlignCenter)
                self.cxui.tableWidget.setItem(k, 2,
                                              QTableWidgetItem(str(ctime)))
                self.cxui.tableWidget.item(k,
                                           2).setTextAlignment(Qt.AlignCenter)
                self.cxui.tableWidget.setItem(k, 3, QTableWidgetItem(str(st)))
                self.cxui.tableWidget.item(k,
                                           3).setTextAlignment(Qt.AlignCenter)
                print(i)
            return
            #return QMessageBox.information(self, "提示", '请出入查询条件...', QMessageBox.Yes, QMessageBox.Yes)
        s = ''
        if no:
            s += "and no like '%%{}%%'".format(no, )
        if name:
            s += "and name like '%%{}%%'".format(name, )
        sql = "select name, no, ctime,st from qds where 1=1" + ' ' + s + 'order by ctime desc limit 7'
        print(sql)
        data = obj.get_list(sql, [])
        if len(data) <= 0:
            return QMessageBox.information(self, "提示", '查询无记录...',
                                           QMessageBox.Yes, QMessageBox.Yes)
        for k, i in enumerate(data):
            name = i[0]
            no = i[1]
            ctime = i[2]
            st = i[3]
            self.cxui.tableWidget.insertRow(k)
            self.cxui.tableWidget.setItem(k, 0, QTableWidgetItem(str(no)))
            self.cxui.tableWidget.item(k, 0).setTextAlignment(Qt.AlignCenter)
            self.cxui.tableWidget.setItem(k, 1, QTableWidgetItem(str(name)))
            self.cxui.tableWidget.item(k, 1).setTextAlignment(Qt.AlignCenter)
            self.cxui.tableWidget.setItem(k, 2, QTableWidgetItem(str(ctime)))
            self.cxui.tableWidget.item(k, 2).setTextAlignment(Qt.AlignCenter)
            self.cxui.tableWidget.setItem(k, 3, QTableWidgetItem(str(st)))
            self.cxui.tableWidget.item(k, 3).setTextAlignment(Qt.AlignCenter)
            print(i)
示例#10
0
文件: main.py 项目: Fesmat/CamPaint
class CameraMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi('MainWin.ui', self)
        self.setWindowTitle('CamPaint')
        self.setWindowIcon(QIcon('main_icon.ico'))
        self.setCentralWidget(self.tabWidget)
        # Загружаем камеру, холст, sql файл и задаем цвета кнопок
        self.load_cam()
        self.load_painter()
        self.load_sql()
        self.load_colors()

    def load_cam(self):
        self.cam_page.setLayout(self.cam_page_lay)
        self.error_cam.hide()
        self.camera = QCameraInfo.defaultCamera()
        # Проверяем, что камера сущетсвует
        # Если нет, то переключаемся на вторую вкладку
        if self.camera.isNull():
            dialog = QErrorMessage()
            dialog.setWindowTitle('Warning')
            dialog.showMessage(
                'Not enough cameras, the app will only be available in drawing mode'
            )
            dialog.exec()
            self.error_cam.show()
            self.cam_page.setEnabled(False)
            self.tabWidget.setCurrentIndex(1)
        # Если да, то на первую
        else:
            self.tabWidget.setCurrentIndex(0)
            self.camera = QCamera(self.camera)
            self.view_cam = QCameraViewfinder(self)
            self.view_cam.setMediaObject(self.camera)
            self.view_cam.setAutoFillBackground(True)
            self.camera.setViewfinder(self.view_cam)
            self.box_lay = QVBoxLayout(self)
            self.box_lay.addWidget(self.view_cam)
            self.scrolling.setLayout(self.box_lay)
            # Запускаем камеру
            self.camera.start()
            # Подвязываем кнопку к слоту со снимком
            self.bt_cam.clicked.connect(self.make_ph)
            # Можно зумить фотографию
            self.zoom.valueChanged.connect(self.zoom_pict)

    def make_ph(self):
        self.camera.setCaptureMode(QCamera.CaptureStillImage)
        self.capt = QCameraImageCapture(self.camera)
        # Останавливаем съемку
        self.camera.searchAndLock()
        # Вызываем диалог и иохранением файла
        dial = QFileDialog.getSaveFileName(
            self, 'Save file', '',
            'Картинка (*.jpg);;Картинка (*.png);;Все файлы (*)')[0]
        if dial:
            self.capt.capture(dial)
            self.camera.unlock()

    def zoom_pict(self, value):
        # Вычисляем зум камеры по функции zoom=1.0 + value * 3 / 99
        # 1.0 - обязательный параметр
        QCameraFocus.zoomTo(self.camera.focus(), 1.0 + value * 3 / 99, 1.0)

    def load_painter(self):
        # Загружаем холст
        self.paint_page.setLayout(self.paint_page_lay)
        # Текущий цвет - черный, ширина кисти - 10
        self.now_col = QColor(0, 0, 0)
        self.now_width = 10
        self.point_width.setValue(10)
        # Подвязываем кнопку с изменением ширины кисти к соответсвующему слоту
        self.point_width.valueChanged.connect(self.change_width)
        # Создаем холст как экземпляр класса Canvas из доп.модуля Canvas
        self.canvas = Canvas.Canvas(self.main_paint_widg)
        self.canvas.move(1, 1)
        self.canvas.resize(self.main_paint_widg.width() - 1,
                           self.main_paint_widg.height() - 1)
        print(self.main_paint_widg.size(), self.canvas.size(),
              self.border_lab.size())
        # Устанавливаем границы рамки
        self.border_lab.setStyleSheet(
            'border-style: solid; border-width: 2px; border-color: black;')
        self.canvas.setStyleSheet('background-color: white;')
        # Устанавливаем сильный фокус для перехвата всех событий
        # клавиатуры и мыши
        self.setFocusPolicy(Qt.StrongFocus)
        # Подвязываем действия из меню к слотам
        self.actionSave.triggered.connect(self.save_file)
        self.actionSave_as.triggered.connect(self.save_as_file)
        self.actionOpen.triggered.connect(self.open_file)
        self.actionReference.triggered.connect(self.open_reference)
        # и кнопку очистки холста, а также задания цвета кисти
        self.bt_clear.clicked.connect(self.clear_canvas)
        self.bt_set_color.clicked.connect(self.set_color_with_bt)
        # Имя файла изначально не задано, файл не сохранен
        self.file_name = ''
        self.saved = False
        self.resizeEvent(QResizeEvent(self.size(), self.size()))

    def change_width(self, value):
        self.now_width = value

    def keyPressEvent(self, event):
        # Обрабатываем события клавитатуры
        if int(event.modifiers()) == Qt.CTRL and event.key() == Qt.Key_Z:
            # Функция 'назад', удаляем все объекты, которые нарисовали
            if self.canvas.obj:
                del self.canvas.obj[-1]
                self.canvas.update()
        elif int(event.modifiers()) == Qt.CTRL and event.key() == Qt.Key_S:
            # Функция 'сохранить', сохраняем файл, если есть изменения
            if self.canvas.obj:
                self.save_file()
        elif int(event.modifiers()) == Qt.CTRL and event.key() == Qt.Key_O:
            # Функция 'открыть', открываем файл
            self.open_file()
        elif int(event.modifiers()) == Qt.CTRL and event.key() == Qt.Key_H:
            # Функция 'справка', открываем справку
            self.open_reference()

    def resizeEvent(self, event):
        # При изменении размеров окна, устанавливаем соответствующие размеры холста и рамки
        self.canvas.resize(self.main_paint_widg.width() - 1,
                           self.main_paint_widg.height() - 1)
        self.border_lab.resize(self.main_paint_widg.width(),
                               self.main_paint_widg.height())

    def save_as_file(self):
        # Сохранение файла как
        dial = \
            QFileDialog.getSaveFileName(self, 'Save file as', '', 'Картинка (*.jpg);;Картинка (*.png);;Все файлы (*)')[
                0]
        if dial:
            # Захватываем изображжение с холста и сохраняем
            pixmap = QPixmap(self.canvas.grab())
            pixmap.save(dial)
            # Сохраняем имя файла в переменной self.file_name, чтобы использовать в функции save_file
            # Очищаем нарисованные объекты, так как уже их сохранили
            self.file_name = dial
            self.saved = True
            self.canvas.obj = []

    def save_file(self):
        # Если имя файла выбрано, просто сохраняем
        if self.file_name:
            pixmap = QPixmap(self.canvas.grab())
            pixmap.save(self.file_name)
            self.saved = True
            self.canvas.obj = []
        # В ином случае, сохраняем как
        else:
            self.save_as_file()

    def open_file(self):
        # Открываем новый файл
        dial = QFileDialog.getOpenFileName(
            self, 'Open file', '',
            'Картинка (*.jpg);;Картинка (*.png);;Все файлы (*)')[0]
        if dial:
            # Если старый файл не сохранен, предлагаем сохранить его
            if self.canvas.obj and not self.saved:
                dial2 = Dialogs.Message()
                res = dial2.exec()
                if res == dial2.Save:
                    self.save_file()
                if res == dial2.Cancel:
                    pass
            # Сохраняем новое имя файла, вызываем функцию open_file в экземпляре холста
            self.file_name = dial
            self.canvas.obj = []
            self.canvas.open_file()

    def open_reference(self):
        dial = Dialogs.Reference()
        dial.exec()

    def clear_canvas(self):
        # Очищаем нарисованные объекты
        self.canvas.obj.clear()
        self.canvas.update()

    def set_color(self, color):
        # Устанавливаем текущий цвет
        self.now_col = color
        red, green, blue = color.red(), color.green(), color.blue()
        # Подключаемся к базе данных в папке проекта
        # и добавляем его к любимым цветам пользователя
        con = sqlite3.connect('own_colors_db.db')
        cur = con.cursor()
        colors = cur.execute(
            f'''SELECT * from colors WHERE red={red} and green={green} and blue={blue}'''
        ).fetchall()
        if colors:
            id = colors[0][0]
            cur.execute(
                f'''UPDATE colors SET counts=counts + 1 WHERE id={id}''')
        else:
            last_id = cur.execute(
                f'''SELECT id from colors''').fetchall()[-1][0]
            cur.execute(
                f'''INSERT INTO colors VALUES ({last_id + 1}, {red}, {green}, {blue}, 1)'''
            )
        con.commit()
        con.close()

    def set_color_with_bt(self):
        # Слот для кнопки выбора цвета
        color = QColorDialog.getColor()
        self.set_color(color)

    def closeEvent(self, event):
        # Закрываем файл, обнуляя значение зума
        self.zoom.setValue(1)
        # И предлагаем сохранить файл, если он не сохранен
        if self.canvas.obj and not self.saved:
            dial = Dialogs.Message()
            res = dial.exec()
            if res == dial.Save:
                self.save_file()
            if res == dial.Cancel:
                event.ignore()

    def load_sql(self):
        # При отсутствии цветов в базе данных(в первом открытии приложения)
        # добавляем в базу данных новый цвет - черный
        con = sqlite3.connect('own_colors_db.db')
        cur = con.cursor()
        len_sql = len(cur.execute(f'''SELECT * from colors''').fetchall())
        if len_sql == 0:
            cur.execute('''INSERT INTO colors VALUES (1, 0, 0, 0, 1)''')
        con.commit()
        con.close()

    def load_colors(self):
        # Загружаем цвета в кнопки любимых цветов пользователя
        colors = []
        con = sqlite3.connect('own_colors_db.db')
        cur = con.cursor()
        ex_colors = sorted(cur.execute(
            '''SELECT red, green, blue, counts from colors''').fetchall(),
                           key=lambda i: i[3])[:21]
        ex_colors = [(i[0], i[1], i[2]) for i in ex_colors]
        colors.extend(ex_colors)
        # Если цветов недостаточно, заполняем кнопки случайными цветами
        # вдруг какой-нибудь из них ползователю понравится
        if len(colors) < 20:
            for i in range(20 - len(colors)):
                new_color = (randrange(256), randrange(256), randrange(256))
                while new_color in colors:
                    new_color = (randrange(256), randrange(256),
                                 randrange(256))
                colors.append(new_color)
        # Сохраняем цвета кнопок в словарь, где ключ - кнопка, значение - цвет
        # А также подключаем кнопки к слоту и изменением цвета
        self.bt_colors_dict = {}
        for i in range(4):
            for j in range(5):
                exec(
                    f'self.bt{i}{j}.setStyleSheet("background:rgb({colors[0][0]}, {colors[0][1]}, {colors[0][2]});")'
                )
                color = QColor(colors[0][0], colors[0][1], colors[0][2])
                exec(f'self.bt_colors_dict[self.bt{i}{j}] = color')
                exec(f'self.bt{i}{j}.clicked.connect(self.set_color_with_bts)')
                del colors[0]

    def set_color_with_bts(self):
        # Слот для установки цвета кисти
        self.set_color(self.bt_colors_dict[self.sender()])
示例#11
0
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

from PyQt5.QtMultimedia import QCamera, QCameraImageCapture
from PyQt5 import QtMultimediaWidgets

cm = QCamera()
viewfinder = QtMultimediaWidgets.QCameraViewfinder()
viewfinder.show()
cm.setViewfinder(viewfinder)

cp = QCameraImageCapture(cm)
cm.setCaptureMode(cm.CaptureStillImage)
cm.start()
cm.searchAndLock()

cp.capture()

cm.unlock()
示例#12
0
class Camera(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initializeUI()

    def initializeUI(self):
        """
        Initialize the window and display its contents to the screen
        """
        self.setGeometry(100, 100, 600, 400)
        self.setWindowTitle('12.2 – Camera GUI')

        self.setupWindows()

        self.show()

    def setupWindows(self):
        """
        Set up QMdiArea parent and subwindows.
        Add available cameras on local system as items to 
        list widget.
        """
        # Create images directory if it does not already exist
        path = 'images'
        if not os.path.exists(path):
            os.makedirs(path)

        # Set up list widget that will display identified
        # cameras on your computer.
        picture_label = QLabel("Press 'Spacebar' to take pictures.")
        camera_label = QLabel("Available Cameras")
        self.camera_list_widget = QListWidget()
        self.camera_list_widget.setAlternatingRowColors(True)

        # Add availableCameras to a list to be displayed in
        # list widget. Use QCameraInfo() to list available cameras.
        self.cameras = list(QCameraInfo().availableCameras())
        for camera in self.cameras:
            self.list_item = QListWidgetItem()
            self.list_item.setText(camera.deviceName())
            self.camera_list_widget.addItem(self.list_item)

        # Create button that will allow user to select camera
        choose_cam_button = QPushButton("Select Camera")
        choose_cam_button.clicked.connect(self.selectCamera)

        # Create child widgets and layout for camera controls subwindow
        controls_gbox = QGroupBox()
        controls_gbox.setTitle("Camera Controls")

        v_box = QVBoxLayout()
        v_box.addWidget(picture_label, alignment=Qt.AlignCenter)
        v_box.addWidget(camera_label)
        v_box.addWidget(self.camera_list_widget)
        v_box.addWidget(choose_cam_button)

        controls_gbox.setLayout(v_box)

        controls_sub_window = QMdiSubWindow()
        controls_sub_window.setWidget(controls_gbox)
        controls_sub_window.setAttribute(Qt.WA_DeleteOnClose)

        # Create view finder subwindow
        self.view_finder_window = QMdiSubWindow()
        self.view_finder_window.setWindowTitle("Camera View")
        self.view_finder_window.setAttribute(Qt.WA_DeleteOnClose)

        # Create QMdiArea widget to manage subwindows
        mdi_area = QMdiArea()
        mdi_area.tileSubWindows()
        mdi_area.addSubWindow(self.view_finder_window)
        mdi_area.addSubWindow(controls_sub_window)

        # Set mdi_area widget as the central widget of main window
        self.setCentralWidget(mdi_area)

    def setupCamera(self, cam_name):
        """
        Create and setup camera functions.
        """
        for camera in self.cameras:
            # Select camera by matching cam_name to one of the
            # devices in the cameras list.
            if camera.deviceName() == cam_name:
                self.cam = QCamera(camera)  # Construct QCamera device

                # Create camera viewfinder widget and add it to the
                # view_finder_window.
                self.view_finder = QCameraViewfinder()
                self.view_finder_window.setWidget(self.view_finder)
                self.view_finder.show()

                # Sets the view finder to display video
                self.cam.setViewfinder(self.view_finder)

                # QCameraImageCapture() is used for taking
                # images or recordings.
                self.image_capture = QCameraImageCapture(self.cam)

                # Configure the camera to capture still images.
                self.cam.setCaptureMode(QCamera.CaptureStillImage)
                self.cam.start()  # Slot to start the camera
            else:
                pass

    def selectCamera(self):
        """
        Slot for selecting one of the available cameras displayed 
        in list widget. 
        """
        try:
            if self.list_item.isSelected():
                camera_name = self.list_item.text()
                self.setupCamera(camera_name)
            else:
                print("No camera selected.")
                pass
        except:
            print("No cameras detected.")

    def keyPressEvent(self, event):
        """
        Handle the key press event so that the camera takes images.
        """
        if event.key() == Qt.Key_Space:
            try:
                self.cam.searchAndLock()
                self.image_capture.capture("images/")
                self.cam.unlock()
            except:
                print("No camera in viewfinder.")
示例#13
0
class LiveFeedWidget(QGraphicsView):
    class _State(Enum):
        Init = "Init"
        Idle = "Idle"
        Preparing = "Preparing"
        WaitingForCapture = "WaitingForCapture"

    error = pyqtSignal(str)
    image_captured = pyqtSignal(QImage)
    initialized = pyqtSignal()

    def __init__(
        self,
        camera: Camera,
        is_mirrored: bool,
        mask: Mask,
        parent=None,
    ):
        super().__init__(parent=parent)
        self._is_mirrored = is_mirrored
        self._mask = mask

        self._state = LiveFeedWidget._State.Init

        self._video_item = QGraphicsVideoItem()
        # I think this is the size in pixels on the screen?
        self._video_item.setSize(QSizeF(self._mask.size))
        # TODO I think this will not draw centrally?  If not should fix this
        self._video_item.setAspectRatioMode(Qt.KeepAspectRatioByExpanding)
        if self._is_mirrored:
            self._video_item.setTransform(QTransform().scale(-1, 1))

        self.setMask(self._mask.clip_region)

        self._scene: OverlayTextGraphicsScene = OverlayTextGraphicsScene(
            self._mask.size)
        self._scene.addItem(self._video_item)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setScene(self._scene)

        # Setup camera
        #
        self._camera = camera
        self._camera.setViewfinder(self._video_item)
        self._camera.setCaptureMode(QCamera.CaptureStillImage)
        self._camera.error.connect(self._on_camera_error)
        self._camera.statusChanged.connect(self._on_camera_status_changed)

        # Setup capture
        #
        self._capture = QCameraImageCapture(self._camera)
        self._capture.setCaptureDestination(
            QCameraImageCapture.CaptureToBuffer)
        self._capture.imageCaptured.connect(self._image_captured)
        self._capture.error.connect(self._on_capture_error)

        self._camera.start()

        logger.info("Camera started")

    def set_overlay_text(self, text: str):
        self._scene.set_overlay_text(text)

    def prepare(self):
        if self._state != LiveFeedWidget._State.Idle:
            logger.warning("Dropping call to prepare when in state: %s",
                           self._state)
        else:
            self._state = LiveFeedWidget._State.Preparing
            self._camera.searchAndLock()

    def trigger_capture(self):
        if self._state != LiveFeedWidget._State.Preparing:
            logger.warning(
                "Dropping call to trigger_capture when in state: %s",
                self._state)
        else:
            logger.debug("trigger_capture")
            self._state = LiveFeedWidget._State.WaitingForCapture
            self._capture.capture()

    # noinspection PyPep8Naming
    def _on_camera_error(self, QCamera_Error: int):
        self._state = LiveFeedWidget._State.Idle
        self.error.emit(f"Camera error, code: {QCamera_Error}")

    # noinspection PyPep8Naming
    def _on_capture_error(self,
                          p_int=None,
                          QCameraImageCapture_Error=None,
                          p_str=None):
        self._state = LiveFeedWidget._State.Idle
        self.error.emit(
            f"Capture error: {p_int} / {QCameraImageCapture_Error} / {p_str}")

    def _image_captured(self, id_: int, image: QImage):
        if self._state != LiveFeedWidget._State.WaitingForCapture:
            logger.warning("Dropping _image_captured when in state: %s",
                           self._state)
        self._state = LiveFeedWidget._State.Idle
        logger.debug("image captured: %s %s", id_, image)
        self._camera.unlock()

        # TODO If I don't unload and the reload the camera, gstreamer dies
        #  with CameraBin error: "Internal data stream error.", not sure why
        #  :(
        self._camera.unload()

        self.image_captured.emit(_mirror_if_necessary(image,
                                                      self._is_mirrored))

    def reload(self):
        # See comment on _image_captured
        self._camera.start()

    def _on_camera_status_changed(self, status):
        logger.debug("_on_camera_status_changed: %s", status)
        if status == QCamera.ActiveStatus:
            self._state = LiveFeedWidget._State.Idle
            self.initialized.emit()
示例#14
0
class AvatarWidget(QWizardPage):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSubTitle(self.tr("<h2>Create Your Avatar</h2>"))

        vlayout = QVBoxLayout(self)

        labelLayout = QHBoxLayout()
        labelImage = QLabel()
        labelImage.setPixmap(
            QPixmap(":/data/images/preferences-desktop-personal.png"))
        labelImage.setMaximumSize(64, 64)
        labelLayout.addWidget(labelImage)

        label = QLabel(self)
        label.setWordWrap(True)
        label.setText(
            self.
            tr("<p>This screen helps you set your <strong>user picture</strong>. You can either choose an image from a \
        file or you can capture an image from your camera. Select an option from the <strong>options</strong> menu.</p>"
               ))
        labelLayout.addWidget(label)
        vlayout.addLayout(labelLayout)

        vlayout.addItem(
            QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred))

        centerLayout = QHBoxLayout()
        centerLayout.addItem(
            QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))

        groupBox = QGroupBox()
        groupBox.setMaximumWidth(500)
        vlayout2 = QVBoxLayout(groupBox)
        hlayout = QHBoxLayout()

        comboBox = QComboBox()
        comboBox.setMinimumWidth(250)
        comboBox.addItems([self.tr("Options"), self.tr("Choose an image...")])

        #Camera control
        self.cameraInfo = None
        self.camera = None
        self.cameraImageCapture = None
        cameras = QCameraInfo.availableCameras()

        if len(cameras):
            self.cameraInfo = cameras[0]
            comboBox.addItem(self.tr("Camera ") + self.cameraInfo.deviceName())
            self.camera = QCamera(self.cameraInfo)
            self.camera.setCaptureMode(QCamera.CaptureStillImage)
            self.cameraImageCapture = QCameraImageCapture(self.camera)
            self.imageProcessing = self.camera.imageProcessing()
            self.imageProcessing.setWhiteBalanceMode(
                QCameraImageProcessing.WhiteBalanceSunlight)
            self.imageProcessing.setContrast(1)
            self.imageProcessing.setSaturation(1)
            self.imageProcessing.setSharpeningLevel(1)
            self.imageProcessing.setDenoisingLevel(1)
            #self.imageProcessing.setColorFilter(QCameraImageProcessing.ColorFilterWhiteboard) #FIXME Qt5.5
            self.cameraImageCapture.imageCaptured.connect(self.imageCapture)

        self.buttonCam = QPushButton()
        self.buttonCam.setText(self.tr("Capture"))
        self.buttonCam.setIcon(QIcon(":/data/images/webcamreceive.png"))
        self.buttonCam.setVisible(False)

        self.buttonReplay = QPushButton()
        self.buttonReplay.setText(self.tr("Recapture"))
        self.buttonReplay.setIcon(QIcon(":/data/images/view-refresh.png"))
        self.buttonReplay.setVisible(False)

        hlayout.addWidget(comboBox)
        hlayout.addItem(
            QSpacerItem(300, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))
        hlayout.addWidget(self.buttonCam)
        hlayout.addWidget(self.buttonReplay)

        vlayout2.addLayout(hlayout)

        hlayout2 = QHBoxLayout()

        hlayout2.addItem(
            QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))

        self.cameraLabel = QLabel()
        self.cameraLabel.setScaledContents(True)
        self.cameraLabel.setStyleSheet("background-color: black;")
        self.cameraLabel.setMinimumSize(320, 240)
        self.cameraLabel.setMaximumSize(320, 240)

        self.cameraView = QCameraViewfinder()
        self.cameraView.setMaximumSize(320, 240)
        self.cameraView.setMinimumSize(320, 240)
        self.cameraView.hide()

        hlayout2.addWidget(self.cameraLabel)
        hlayout2.addWidget(self.cameraView)

        hlayout2.addItem(
            QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))
        vlayout2.addLayout(hlayout2)

        centerLayout.addWidget(groupBox)
        centerLayout.addItem(
            QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))
        vlayout.addLayout(centerLayout)
        vlayout.addItem(
            QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred))

        comboBox.currentIndexChanged.connect(self.avatarSelect)
        self.buttonCam.clicked.connect(self.buttonCamChanged)
        self.buttonReplay.clicked.connect(self.buttonReplayChanged)

        self.userAvatar = None

    def avatarSelect(self, index):
        if index == 0:
            if self.camera != None:
                self.camera.stop()
            self.buttonReplay.hide()
            self.buttonCam.hide()
            self.cameraView.hide()
            self.cameraLabel.show()
        elif index == 1:
            if self.camera != None:
                self.camera.stop()
            self.userAvatar = None
            self.buttonReplay.hide()
            self.buttonCam.hide()
            self.cameraView.hide()
            self.cameraLabel.show()
            file_url, file_type = QFileDialog.getOpenFileName(
                self, self.tr("Choose Avatar"), QDir.homePath(),
                "Image (*.png *.jpg)")
            if file_url != "":
                p = QPixmap(file_url)
                self.cameraLabel.setPixmap(p)
                self.userAvatar = file_url
        elif index == 2:
            self.userAvatar = None
            self.cameraLabel.hide()
            self.cameraView.show()
            self.camera.setViewfinder(self.cameraView)
            self.camera.start()
            self.buttonCam.setVisible(True)
            self.buttonReplay.hide()

    def buttonCamChanged(self):
        self.buttonCam.hide()
        self.buttonReplay.show()
        self.camera.searchAndLock()
        self.cameraImageCapture.capture("/tmp/avatar.png")
        self.camera.unlock()
        self.userAvatar = "/tmp/avatar.png"

    def buttonReplayChanged(self):
        self.userAvatar = None
        self.buttonReplay.hide()
        self.buttonCam.show()
        self.camera.start()
        self.cameraLabel.hide()
        self.cameraView.show()

    def imageCapture(self, id, preview):
        pixmap = QPixmap.fromImage(preview)
        self.camera.stop()
        self.cameraView.hide()
        self.cameraLabel.show()
        self.cameraLabel.setPixmap(pixmap)

    def execute(self):
        if self.userAvatar:
            if os.path.exists(os.path.join(os.environ["HOME"], ".face.icon")):
                os.remove(os.path.join(os.environ["HOME"], ".face.icon"))
            shutil.copy(self.userAvatar,
                        os.path.join(os.environ["HOME"], ".face.icon"))
示例#15
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.cameraInfo = QCameraInfo.defaultCamera()
        self.camera = QCamera(self.cameraInfo)
        self.camera.setCaptureMode(QCamera.CaptureStillImage)
        self.imageCapture = QCameraImageCapture(self.camera)
        self.imageCapture.imageCaptured.connect(self.imageCaptured)
        self.imageCapture.imageSaved.connect(self.imageSaved)
        self.currentPreview = QImage()

        toolBar = QToolBar()


        self.addToolBar(toolBar)

        fileMenu = self.menuBar().addMenu("&File")
        shutterIcon = QIcon("/Users/thethelafaltein/PycharmProjects/ResNetApplication/res/img/shutter.svg")
        self.takePictureAction = QAction(shutterIcon, "&Take Picture", self,
                                         shortcut="Ctrl+T",
                                         triggered=self.takePicture)
        self.takePictureAction.setToolTip("Take Picture")
        fileMenu.addAction(self.takePictureAction)
        toolBar.addAction(self.takePictureAction)

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

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

        self.tabWidget = QTabWidget()
        self.setCentralWidget(self.tabWidget)


        self.cameraViewfinder = QCameraViewfinder()
        self.camera.setViewfinder(self.cameraViewfinder)
        self.tabWidget.addTab(self.cameraViewfinder, "Viewfinder")




        if self.camera.status() != QCamera.UnavailableStatus:
            name = self.cameraInfo.description()
            self.setWindowTitle("PySide2 Camera Example (" + name + ")")
            self.statusBar().showMessage("Starting: '" + name + "'", 5000)
            self.camera.start()
        else:
            self.setWindowTitle("Object classifier")
            self.takePictureAction.setEnabled(False)
            self.statusBar().showMessage("Camera unavailable", 5000)

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


    def predicition(self,filename):

        model = resnet50.ResNet50()

        img = image.load_img(filename,
                             target_size=(224, 224))


        x = image.img_to_array(img)


        x = np.expand_dims(x, axis=0)


        x = resnet50.preprocess_input(x)


        predictions = model.predict(x)

        predicted_classes = resnet50.decode_predictions(predictions, top=9)

        top_value = []

        for imagenet_id, name, likelihood in predicted_classes[0]:
            top_value.append(name)

        if len(top_value)>0:
            return top_value[0]
        else:
            return "Unknown"


    def createAudio(self,text):

        language = 'en'

        myobj = gTTS(text=text, lang=language, slow=False)

        myobj.save(text+".mp3")

        return text+".mp3"


    def takePicture(self):
        self.currentPreview = QImage()
        self.camera.searchAndLock()
        self.imageCapture.capture(self.nextImageFileName())
        self.camera.unlock()

    def imageCaptured(self, id, previewImage):
        self.currentPreview = previewImage

    def imageSaved(self, id, fileName):

        predicitionName = self.predicition(fileName)

        audiofile = self.createAudio(predicitionName)

        index = self.tabWidget.count()

        imageView = ImageView(self.currentPreview, fileName,audiofile)

        self.tabWidget.addTab(imageView, predicitionName)
        self.tabWidget.setCurrentIndex(index)
示例#16
0
class Window(QWidget):

    _Constant_recognition = 0.8

    
    # конструктор формы
    def __init__(self):
        super().__init__()
        self._Client = Biometric_Client(url='https://expasoft.com', port=2133,
                                        subscription_key='9fc9474b4bd16b492276eee41763a3cb')
        self.imgName = os.getcwd() + "\img\currentPhoto.jpg"
        self.imgName0 = os.getcwd() + "\img\currentPhoto0.jpg"
        self.imgName1 = os.getcwd() + "\img\dbPhoto0.jpg"
        self.setObjectName("FormMain")
        self.setWindowTitle("БиоСКУД Watchman")
        self.resize(1024, 600)

        self.groupBoxCamera = QtWidgets.QGroupBox(self)
        self.groupBoxCamera.setObjectName("groupBoxCamera")
        self.groupBoxCamera.setTitle("")
        self.groupBoxCamera.setGeometry(QtCore.QRect(10, 10, 500, 371))
        
        self.labelCameraTitle = QtWidgets.QLabel(self.groupBoxCamera)
        self.labelCameraTitle.setObjectName("labelCameraTitle")
        self.labelCameraTitle.setText("Изображение с камеры")
        self.labelCameraTitle.setGeometry(QtCore.QRect(160, 10, 181, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.labelCameraTitle.setFont(font)
        
        self.CameraStream = QVideoWidget(self)
        self.CameraStream.setObjectName("videoCameraStream")
        self.CameraStream.setGeometry(QtCore.QRect(10, 50, 481, 261))
        self.CameraStream.setMinimumSize(QtCore.QSize(241, 0))
       
        self.pushButtonRecognition = QtWidgets.QPushButton(self.groupBoxCamera)
        self.pushButtonRecognition.setObjectName("pushButtonRecognition")
        self.pushButtonRecognition.setText("Распознать")
        self.pushButtonRecognition.setGeometry(QtCore.QRect(10, 310, 481, 51))
        self.pushButtonRecognition.clicked.connect(self.identifyPersonBegin)
        
        self.pushButtonLog = QtWidgets.QPushButton(self)
        self.pushButtonLog.setObjectName("pushButtonLog")
        self.pushButtonLog.setText("Журнал")
        self.pushButtonLog.setGeometry(QtCore.QRect(10, 460, 121, 61))
        self.pushButtonLog.clicked.connect(self.OpenLogFile)
        
        self.pushButtonDb = QtWidgets.QPushButton(self)
        self.pushButtonDb.setObjectName("pushButtonDb")
        self.pushButtonDb.setText("База данных")
        self.pushButtonDb.setGeometry(QtCore.QRect(10, 390, 121, 61))
        self.pushButtonDb.clicked.connect(self.OpenArchivist)
        
        self.groupBoxRecognition = QtWidgets.QGroupBox(self)
        self.groupBoxRecognition.setObjectName("groupBoxRecognition")
        self.groupBoxRecognition.setTitle("")
        self.groupBoxRecognition.setGeometry(QtCore.QRect(520, 10, 500, 581))

        self.pushButtonExit = QtWidgets.QPushButton(self)
        self.pushButtonExit.setObjectName("pushButtonExit")
        self.pushButtonExit.setText("Выйти")
        self.pushButtonExit.setGeometry(QtCore.QRect(10, 530, 121, 61))
        self.pushButtonExit.clicked.connect(self.ExitProgream)

        self.labelPersonName = QtWidgets.QLabel(self.groupBoxRecognition)
        self.labelPersonName.setObjectName("labelPersonName")
        self.labelPersonName.setText("")
        self.labelPersonName.setGeometry(QtCore.QRect(20, 320, 271, 31))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.labelPersonName.setFont(font)
        
        self.labelCurrentPhoto = QtWidgets.QLabel(self.groupBoxRecognition)
        self.labelCurrentPhoto.setObjectName("labelCurrentPhoto")
        self.labelCurrentPhoto.setText("")
        self.labelCurrentPhoto.setGeometry(QtCore.QRect(10, 40, 241, 261))
        self.labelCurrentPhoto.setMinimumSize(QtCore.QSize(241, 0))
        self.labelCurrentPhoto.setAlignment(QtCore.Qt.AlignCenter)
        
        self.labelPersonJob = QtWidgets.QLabel(self.groupBoxRecognition)
        self.labelPersonJob.setObjectName("labelPersonJob")
        self.labelPersonJob.setText("")
        self.labelPersonJob.setGeometry(QtCore.QRect(20, 360, 171, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.labelPersonJob.setFont(font)

        self.labelPersonInf = QtWidgets.QLabel(self.groupBoxRecognition)
        self.labelPersonInf.setObjectName("labelPersonJob")
        self.labelPersonInf.setText("")
        self.labelPersonInf.setGeometry(QtCore.QRect(20, 400, 171, 21))
        font = QtGui.QFont()
        font.setPointSize(8)
        self.labelPersonInf.setFont(font)
        
        self.labelAccess = QtWidgets.QLabel(self.groupBoxRecognition)
        self.labelAccess.setObjectName("labelAccess")
        self.labelAccess.setText("<html><head/><body><p align=\"center\">Допущен</p></body></html>")
        self.labelAccess.setGeometry(QtCore.QRect(10, 490, 481, 81))
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(76, 197, 32))
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
        self.labelAccess.setPalette(palette)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.labelAccess.setFont(font)
        self.labelAccess.setAcceptDrops(False)
        self.labelAccess.setAutoFillBackground(True)
        self.labelAccess.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.labelAccess.setFrameShadow(QtWidgets.QFrame.Plain)
        self.labelAccess.setTextFormat(QtCore.Qt.AutoText)
        self.labelAccess.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse)

        self.labelDbPhoto = QtWidgets.QLabel(self.groupBoxRecognition)
        self.labelDbPhoto.setObjectName("labelDbPhoto")
        self.labelDbPhoto.setText("")
        self.labelDbPhoto.setGeometry(QtCore.QRect(250, 40, 241, 261))
        self.labelDbPhoto.setMinimumSize(QtCore.QSize(241, 0))
        self.labelDbPhoto.setAlignment(QtCore.Qt.AlignCenter)
        
        self.labelCurrentPhotoTitle = QtWidgets.QLabel(self.groupBoxRecognition)
        self.labelCurrentPhotoTitle.setObjectName("labelCurrentPhotoTitle")
        self.labelCurrentPhotoTitle.setText("Текущее фото")
        self.labelCurrentPhotoTitle.setGeometry(QtCore.QRect(80, 10, 111, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.labelCurrentPhotoTitle.setFont(font)

        self.labelDbPhotoTitle = QtWidgets.QLabel(self.groupBoxRecognition)
        self.labelDbPhotoTitle.setObjectName("labelDbPhotoTitle")
        self.labelDbPhotoTitle.setText("Фото в базе")
        self.labelDbPhotoTitle.setGeometry(QtCore.QRect(320, 10, 111, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.labelDbPhotoTitle.setFont(font)

        self.device = QCamera.availableDevices()[0]
        self.camera = QCamera(self.device)
        self.camera.setViewfinder(self.CameraStream)
        self.camera.setCaptureMode(QCamera.CaptureStillImage)
        self.imageCapture=QCameraImageCapture(self.camera)
        self.imageCapture.imageSaved.connect(self.identifyPersonEnd)
        self.camera.start()

    # идентификация человека (фото)
    def identifyPersonBegin(self):
        if self.imageCapture.isReadyForCapture():
            #imgName = os.getcwd() + "\img\currentPhoto.jpg"
            self.camera.searchAndLock()
            self.imageCapture.capture(self.imgName)
            self.camera.unlock()

    # идентификация человека (алгоритм)
    def identifyPersonEnd(self):

        self._Client.get_aligned_faces(self.imgName, "img\currentPhoto")
        
        id_person = self._Client.identify_profile_by_face(self.imgName0, 1, 0).pop("result")[0]
        self._Client.get_profile_image(id_person['profile_id'], id_person['image_id'],self.imgName1)
        self.labelCurrentPhoto.setPixmap(QtGui.QPixmap(self.imgName0))
        self.labelDbPhoto.setPixmap(QtGui.QPixmap(self.imgName1))

        profile = JsonDataBase.GetInfo(id_person['profile_id'])
        if profile != None:
            self.labelPersonName.setText(profile['name'])
            self.labelPersonJob.setText(profile['tag'])
        else:
            self.labelPersonName.setText(profile[''])
            self.labelPersonJob.setText(profile[''])

        if id_person['score'] > self._Constant_recognition :
            palette = QtGui.QPalette()
            brush = QtGui.QBrush(QtGui.QColor(255, 22, 46))
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
            self.labelAccess.setPalette(palette)
            self.labelAccess.setText("<html><head/><body><p align=\"center\">Недопущен</p></body></html>")
        else:
            palette = QtGui.QPalette()
            brush = QtGui.QBrush(QtGui.QColor(76, 197, 32))
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
            self.labelAccess.setPalette(palette)
            self.labelAccess.setText("<html><head/><body><p align=\"center\">Допущен</p></body></html>")
        self.labelPersonInf.setText('id= ' + str(id_person['profile_id'])+' score= '+str(id_person['score']))

    # открыть управление базой данных
    def OpenArchivist(self):
        self.archivist = Archivist.Window()
        self.archivist.show()

    # открыть файл логов
    def OpenLogFile(self):
        os.system("log.txt")

    # выйти из программы
    def ExitProgream(self):
        self.camera.stop()
        self.close()
示例#17
0
class CameraView(QMainWindow):
    """
    Camera view widget

    .ui form is based on pyqt5/examples/multimediawidgets/camera
    """
    def __init__(self, camera, parent=None):
        super(CameraView, self).__init__(parent)

        self.app = QApplication.instance()
        self.camera = camera

        self.ui = ui_camera.Ui_CameraView()
        self.ui.setupUi(self)

        self.setWindowTitle(iWebcamIpfsCapture())

        self.camera.setCaptureMode(QCamera.CaptureStillImage)
        self.camera.stateChanged.connect(self.onCameraStateChange)
        self.camera.error.connect(self.onCameraError)

        # Image capture
        self.imageCapture = QCameraImageCapture(self.camera)
        self.imageCapture.setCaptureDestination(
            QCameraImageCapture.CaptureToBuffer)
        self.imageCapture.imageCaptured.connect(
            lambda reqid, img: ensure(self.handleImage(reqid, img)))
        self.imageCapture.readyForCaptureChanged.connect(self.readyForCapture)

        # Recorder
        self.mediaRecorder = QMediaRecorder(self.camera)
        self.mediaRecorder.durationChanged.connect(self.recDurationChanged)
        self.mediaRecorder.stateChanged.connect(self.updateRecorderState)
        self.mediaRecorder.actualLocationChanged.connect(
            self.recLocationChanged)
        self.mediaRecorder.error.connect(self.onRecorderError)

        self.ui.captureWidget.currentChanged.connect(self.updateCaptureMode)
        self.ui.captureImageButton.clicked.connect(self.captureImage)
        self.ui.closeButton.clicked.connect(self.onClose)
        self.ui.recordButton.clicked.connect(self.record)
        self.ui.pauseButton.clicked.connect(self.pause)
        self.ui.stopButton.clicked.connect(lambda: ensure(self.stop()))
        self.ui.muteButton.toggled.connect(self.setMuted)
        self.ui.pauseButton.hide()

        self.isCapturingImage = False
        self.videoLocation = None

        self.showMaximized()

    def keyPressEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_Escape:
            self.camera.stop()
            self.hide()
            event.accept()
        elif event.key() == Qt.Key_S:
            if self.camera.captureMode() == QCamera.CaptureStillImage:
                self.captureImage()
            event.accept()
        else:
            super(CameraView, self).keyPressEvent(event)

    async def handleImage(self, requestId, img):
        scaledImage = img.scaled(self.ui.viewfinder.size(), Qt.KeepAspectRatio,
                                 Qt.SmoothTransformation)

        self.ui.lastImagePreviewLabel.setPixmap(QPixmap.fromImage(scaledImage))
        self.displayCapturedImage()

        imgFormat = self.ui.captureImageFormat.currentText()

        array = QByteArray()
        buffer = QBuffer(array)
        buffer.open(QIODevice.WriteOnly)
        img.save(buffer, imgFormat)
        buffer.close()

        await self.importImageBuffer(buffer, imgFormat.lower())

        QTimer.singleShot(3000, self.displayViewfinder)

    def recLocationChanged(self, loc):
        pass

    def record(self):
        self.mediaRecorder.record()
        self.videoLocation = self.mediaRecorder.outputLocation()
        self.updateRecordTime()

    def pause(self):
        self.mediaRecorder.pause()

    async def stop(self):
        self.mediaRecorder.stop()
        self.ui.statusbar.showMessage('')

        if self.videoLocation and await questionBoxAsync(
                'Video import', 'Import video to your repository ?'):

            filePath = self.videoLocation.toLocalFile()

            if not os.path.isfile(filePath):
                return messageBox('Could not find captured video')

            basename = os.path.basename(filePath)

            name = inputTextCustom('Video import',
                                   'Video filename',
                                   text=basename)

            if not name:
                return

            if name != basename:
                dst = Path(os.path.dirname(filePath)).joinpath(name)
                shutil.move(filePath, str(dst))
            else:
                dst = Path(filePath)

            if name:
                ensure(self.importVideoRecord(dst, name))

    @ipfsOp
    async def importImageBuffer(self, ipfsop, buffer, extension):
        fModel = ipfsop.ctx.currentProfile.filesModel

        entry = await ipfsop.addBytes(bytes(buffer.data()),
                                      pin=self.ui.pinCapturedPhoto.isChecked())

        if entry:
            if self.ui.copyPhotoToMfs.isChecked():
                await ipfsop.filesLink(entry,
                                       fModel.itemPictures.path,
                                       name='camshot-{id}.{ext}'.format(
                                           id=int(time.time()), ext=extension))

                self.app.mainWindow.fileManagerWidget.refreshItem(
                    fModel.itemPictures)

            if self.ui.copyPhotoCidToClipboard.isChecked():
                self.app.setClipboardText(entry['Hash'])
        else:
            messageBox('Could not import image')

    @ipfsOp
    async def importVideoRecord(self, ipfsop, videoPath, name):
        fModel = ipfsop.ctx.currentProfile.filesModel

        entry = await ipfsop.addPath(str(videoPath),
                                     wrap=True,
                                     pin=self.ui.pinVideo.isChecked())

        if entry:
            # Can remove it from disk now

            try:
                videoPath.unlink()
            except Exception:
                log.debug(f'Could not remove video {videoPath}')

            if self.ui.copyVideoToMfs.isChecked():
                await ipfsop.filesLink(entry,
                                       fModel.itemVideos.path,
                                       name=f'{name}.dirw')

                self.app.mainWindow.fileManagerWidget.refreshItem(
                    fModel.itemVideos)

            if self.ui.copyVideoCidToClipboard.isChecked():
                try:
                    # Copy the video's CID
                    listing = await ipfsop.listObject(entry['Hash'])
                    links = listing['Objects'].pop()['Links']
                    videoCid = links.pop()['Hash']
                    self.app.setClipboardText(videoCid)
                except Exception:
                    # Fall back to copying the directory wrapper
                    self.app.setClipboardText(entry['Hash'])
        else:
            messageBox('Could not import video')

    def setMuted(self, muted):
        self.mediaRecorder.setMuted(muted)

    def captureImage(self):
        self.isCapturingImage = True
        self.imageCapture.capture()

    def updateCaptureMode(self):
        tabIndex = self.ui.captureWidget.currentIndex()
        captureMode = QCamera.CaptureStillImage if tabIndex == 0 else \
            QCamera.CaptureVideo

        if self.camera.isCaptureModeSupported(captureMode):
            self.camera.setCaptureMode(captureMode)

    def onCameraStateChange(self, state):
        if state == QCamera.ActiveState:
            pass
        elif state in (QCamera.UnloadedState, QCamera.LoadedState):
            pass

    def updateRecorderState(self, state):
        if state == QMediaRecorder.StoppedState:
            self.ui.recordButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(True)
            self.ui.stopButton.setEnabled(False)
        elif state == QMediaRecorder.PausedState:
            self.ui.recordButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(False)
            self.ui.stopButton.setEnabled(True)
        elif state == QMediaRecorder.RecordingState:
            self.ui.recordButton.setEnabled(False)
            self.ui.pauseButton.setEnabled(True)
            self.ui.stopButton.setEnabled(True)

    def onRecorderError(self):
        messageBox('Capture Error: {}'.format(
            self.mediaRecorder.errorString()))

    def onCameraError(self):
        messageBox('Camera Error: {}'.format(self.camera.errorString()))

    def recDurationChanged(self, duration):
        self.updateRecordTime()

    def updateRecordTime(self):
        msg = "Recorded {secs} secs".format(
            secs=self.mediaRecorder.duration() // 1000)
        self.ui.statusbar.showMessage(msg)

    def displayViewfinder(self):
        self.ui.stackedWidget.setCurrentIndex(0)

    def displayCapturedImage(self):
        self.ui.stackedWidget.setCurrentIndex(1)

    def readyForCapture(self, ready):
        self.ui.captureImageButton.setEnabled(ready)

    def onClose(self):
        self.camera.stop()
        self.hide()

    def closeEvent(self, event):
        self.camera.stop()
        super().closeEvent(event)
示例#18
0
文件: tomarFoto.py 项目: ykv001/PyQt5
class Widgets(QWidget):
    def __init__(self, dispositivoCamara, parent=None):
        super(Widgets, self).__init__(parent)

        self.parent = parent

        self.estadoFoto = False
        self.byteArrayFoto = QByteArray()

        # ==========================================================

        frame = QFrame(self)
        frame.setFrameShape(QFrame.Box)
        frame.setFrameShadow(QFrame.Sunken)
        frame.setFixedWidth(505)
        frame.setFixedHeight(380)
        frame.move(10, 10)

        # Instancias
        self.paginaVisor = QVideoWidget()
        self.paginaVisor.resize(500, 375)

        self.visor = QCameraViewfinder(self.paginaVisor)
        self.visor.resize(500, 375)

        self.labelFoto = QLabel()
        self.labelFoto.setAlignment(Qt.AlignCenter)
        self.labelFoto.resize(500, 375)

        # QStackedWidget
        self.stackedWidget = QStackedWidget(frame)
        self.stackedWidget.addWidget(self.paginaVisor)
        self.stackedWidget.addWidget(self.labelFoto)
        self.stackedWidget.resize(500, 375)
        self.stackedWidget.move(2, 2)

        # ======================== BOTONES =========================

        self.buttonTomarFoto = QPushButton("Tomar foto", self)
        self.buttonTomarFoto.resize(110, 26)
        self.buttonTomarFoto.move(525, 10)

        self.buttonEliminarFoto = QPushButton("Eliminar foto", self)
        self.buttonEliminarFoto.resize(110, 26)
        self.buttonEliminarFoto.move(525, 50)

        self.buttonGuardarFoto = QPushButton("Guardar foto", self)
        self.buttonGuardarFoto.resize(110, 26)
        self.buttonGuardarFoto.move(525, 82)

        # ======================== EVENTOS =========================

        self.buttonTomarFoto.clicked.connect(self.tomarFoto)
        self.buttonEliminarFoto.clicked.connect(self.eliminarFoto)
        self.buttonGuardarFoto.clicked.connect(self.guardarFoto)

        # ================== FUNCIONES AUTOMÁTICAS =================

        self.setCamara(dispositivoCamara)

# ======================= FUNCIONES ============================

    def setCamara(self, dispositivoCamara):
        if dispositivoCamara.isEmpty():
            self.camara = QCamera()
        else:
            self.camara = QCamera(dispositivoCamara)

        self.camara.stateChanged.connect(self.actualizarEstadoCamara)

        self.capturaImagen = QCameraImageCapture(self.camara)

        self.camara.setViewfinder(self.visor)

        self.actualizarEstadoCamara(self.camara.state())

        self.capturaImagen.imageCaptured.connect(self.procesarImagenCapturada)
        self.capturaImagen.imageSaved.connect(self.imagenGuardada)

        self.camara.isCaptureModeSupported(QCamera.CaptureStillImage)

        self.camara.start()

        self.paginaVisor.update()

    def actualizarDispositivoCamara(self, action):
        self.setCamara(action.data())

    def actualizarEstadoCamara(self, estado):
        if estado == QCamera.ActiveState:
            self.parent.accionIniciarCamara.setEnabled(False)
            self.parent.accionDetenerCamara.setEnabled(True)

            if not self.estadoFoto:
                self.buttonTomarFoto.setEnabled(True)
                self.buttonEliminarFoto.setEnabled(False)
                self.buttonGuardarFoto.setEnabled(False)
        elif estado in (QCamera.UnloadedState, QCamera.LoadedState):
            self.parent.accionIniciarCamara.setEnabled(True)
            self.parent.accionDetenerCamara.setEnabled(False)

            if not self.estadoFoto:
                self.buttonTomarFoto.setEnabled(False)
                self.buttonEliminarFoto.setEnabled(False)
                self.buttonGuardarFoto.setEnabled(False)

    def iniciarCamara(self):
        self.camara.start()

    def detenerCamara(self):
        self.camara.stop()

    def tomarFoto(self):
        rutaFoto = "{}/fotoTemporal.jpg".format(getcwd())
        self.capturaImagen.capture(rutaFoto)

        self.estadoFoto = True

    def procesarImagenCapturada(self, requestId, imagen):
        foto = QPixmap.fromImage(imagen)

        buffer = QBuffer(self.byteArrayFoto)
        buffer.open(QIODevice.WriteOnly)
        buffer.close()
        foto.save(buffer, "PNG")

        fotoEscalada = foto.scaled(self.labelFoto.size())

        self.labelFoto.setPixmap(fotoEscalada)
        self.mostrarImagenCapturada()

    def visualizarVisor(self):
        self.stackedWidget.setCurrentIndex(0)

    def mostrarImagenCapturada(self):
        self.stackedWidget.setCurrentIndex(1)

        self.buttonTomarFoto.setEnabled(False)
        self.buttonEliminarFoto.setEnabled(True)
        self.buttonGuardarFoto.setEnabled(True)

    def imagenGuardada(self, id, nombreFoto):
        if QFile.exists(nombreFoto):
            remove(nombreFoto)

    def eliminarFoto(self):
        self.estadoFoto = False
        self.byteArrayFoto.clear()

        self.labelFoto.clear()

        self.actualizarEstadoCamara(self.camara.state())
        self.visualizarVisor()

    def guardarFoto(self):
        guardarComo, extension = QFileDialog.getSaveFileName(
            self,
            "Guardar como",
            "Foto",
            "JPG (*.jpg);;PNG (*.png);;ICO (*.ico);;BMP (*.bmp)",
            options=QFileDialog.Options())

        if guardarComo:
            foto = QPixmap()
            foto.loadFromData(self.byteArrayFoto, "PNG", Qt.AutoColor)
            foto.save(guardarComo, quality=100)

            QMessageBox.information(
                self, "Guardar foto",
                "Foto guardada con éxito                                 ")

            self.eliminarFoto()
示例#19
0
class UserWidget(QWidget):

    host_name = None
    full_name = None
    user_name = None
    passwd = None
    repasswd = None
    rpasswd = None
    rrepasswd = None

    def __init__(self, parent=None):
        super().__init__()
        self.parent = parent
        self.setStyleSheet("QToolButton {border: none;}")
        self.setLayout(QHBoxLayout())

        left_layout = QVBoxLayout()
        self.layout().addLayout(left_layout)

        self.name_label = QLabel()
        left_layout.addWidget(self.name_label)

        name_layout = QHBoxLayout()
        left_layout.addLayout(name_layout)

        self.name_line = QLineEdit()
        self.name_line.setFixedWidth(450)
        name_layout.addWidget(self.name_line)

        self.name_icon = QLabel()
        self.name_icon.setFixedSize(24, 24)
        self.name_icon.setScaledContents(True)
        name_layout.addWidget(self.name_icon)

        self.user_label = QLabel()
        left_layout.addWidget(self.user_label)

        user_layout = QHBoxLayout()
        left_layout.addLayout(user_layout)

        self.user_line = QLineEdit()
        user_layout.addWidget(self.user_line)

        self.user_icon = QLabel()
        self.user_icon.setScaledContents(True)
        self.user_icon.setFixedSize(24, 24)
        user_layout.addWidget(self.user_icon)

        self.host_label = QLabel()
        left_layout.addWidget(self.host_label)

        host_layout = QHBoxLayout()
        left_layout.addLayout(host_layout)

        self.host_line = QLineEdit()
        host_layout.addWidget(self.host_line)

        self.host_icon = QLabel()
        self.host_icon.setFixedSize(24, 24)
        self.host_icon.setScaledContents(True)
        host_layout.addWidget(self.host_icon)

        self.pass_label = QLabel()
        left_layout.addWidget(self.pass_label)

        pass_layout = QHBoxLayout()
        left_layout.addLayout(pass_layout)

        self.pass_line = QLineEdit()
        self.pass_line.setEchoMode(QLineEdit.Password)
        pass_layout.addWidget(self.pass_line)

        self.pass_icon = QLabel()
        self.pass_icon.setScaledContents(True)
        self.pass_icon.setFixedSize(24, 24)
        pass_layout.addWidget(self.pass_icon)

        repass_layout = QHBoxLayout()
        left_layout.addLayout(repass_layout)

        self.repass_line = QLineEdit()
        self.repass_line.setEchoMode(QLineEdit.Password)
        repass_layout.addWidget(self.repass_line)

        self.repass_icon = QLabel()
        self.repass_icon.setScaledContents(True)
        self.repass_icon.setFixedSize(24, 24)
        repass_layout.addWidget(self.repass_icon)

        self.auto_box = QCheckBox()
        self.auto_box.setChecked(True)
        left_layout.addWidget(self.auto_box)

        self.root_box = QCheckBox()
        self.root_box.setChecked(True)
        left_layout.addWidget(self.root_box)

        rpass_layout = QHBoxLayout()
        left_layout.addLayout(rpass_layout)

        rpass_layout.addSpacerItem(QSpacerItem(0, 40, QSizePolicy.Maximum, QSizePolicy.Expanding))

        self.rpass_line = QLineEdit()
        self.rpass_line.hide()
        self.rpass_line.setEchoMode(QLineEdit.Password)
        rpass_layout.addWidget(self.rpass_line)

        self.rpass_icon = QLabel()
        self.rpass_icon.hide()
        self.rpass_icon.setScaledContents(True)
        self.rpass_icon.setFixedSize(24, 24)
        rpass_layout.addWidget(self.rpass_icon)

        rrepass_layout = QHBoxLayout()
        left_layout.addLayout(rrepass_layout)

        self.rrepass_line = QLineEdit()
        self.rrepass_line.hide()
        self.rrepass_line.setEchoMode(QLineEdit.Password)
        rrepass_layout.addWidget(self.rrepass_line)

        self.rrepass_icon = QLabel()
        self.rrepass_icon.hide()
        self.rrepass_icon.setScaledContents(True)
        self.rrepass_icon.setFixedSize(24, 24)
        rrepass_layout.addWidget(self.rrepass_icon)

        left_layout.addSpacerItem(QSpacerItem(20, 40, QSizePolicy.Maximum, QSizePolicy.Expanding))

        self.layout().addSpacerItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Expanding))

        right_layout = QVBoxLayout()
        self.layout().addLayout(right_layout)

        ######## Camera

        self.cameras = QCameraInfo.availableCameras()

        self.photo_label = QLabel()
        self.photo_label.setFixedSize(192, 192)
        self.photo_label.setScaledContents(True)
        self.photo_label.setPixmap(QPixmap(":/images/user-avatar.svg"))
        self.parent.lilii_settings["avatar"] = None
        right_layout.addWidget(self.photo_label)

        if len(self.cameras):
            self.camera = QCamera(self.cameras[0])
            self.camera.setCaptureMode(QCamera.CaptureStillImage)

            self.image_capture = QCameraImageCapture(self.camera)
            self.image_capture.imageSaved.connect(self.imageConvert)

        button_layout = QHBoxLayout()
        right_layout.addLayout(button_layout)

        self.take_photo = CustomToolButton()
        self.take_photo.setEnabled(len(self.cameras))
        self.take_photo.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.take_photo.setIconSize(QSize(32, 32))
        self.take_photo.setIcon(QIcon(":/images/camera.svg"))
        self.take_photo.setEnterIcon(QIcon(":/images/camera-red.svg"))
        self.take_photo.setLeaveIcon(QIcon(":/images/camera.svg"))
        button_layout.addWidget(self.take_photo)

        self.retake_photo = CustomToolButton()
        self.retake_photo.hide()
        self.retake_photo.setEnabled(len(self.cameras))
        self.retake_photo.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.retake_photo.setIconSize(QSize(32, 32))
        self.retake_photo.setIcon(QIcon(":/images/camera.svg"))
        self.retake_photo.setEnterIcon(QIcon(":/images/camera-red.svg"))
        self.retake_photo.setLeaveIcon(QIcon(":/images/camera.svg"))
        button_layout.addWidget(self.retake_photo)

        self.select_photo = CustomToolButton()
        self.select_photo.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.select_photo.setIconSize(QSize(32, 32))
        self.select_photo.setIcon(QIcon(":/images/users.svg"))
        self.select_photo.setLeaveIcon(QIcon(":/images/users.svg"))
        self.select_photo.setEnterIcon(QIcon(":/images/users-red.svg"))
        button_layout.addWidget(self.select_photo)

        self.layout().addSpacerItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.parent.lilii_settings["auto_login"] = self.auto_box.isChecked()
        self.parent.lilii_settings["root_user"] = self.root_box.isChecked()

        self.auto_box.toggled.connect(self.autoControl)
        self.root_box.toggled.connect(self.rootControl)
        self.host_line.textChanged.connect(self.hostnameControl)
        self.name_line.textChanged.connect(self.fullnameControl)
        self.name_line.textChanged.connect(self.fullnameToUsername)
        self.user_line.textChanged.connect(self.usernameControl)
        self.pass_line.textChanged.connect(self.passwordControl)
        self.repass_line.textChanged.connect(self.repasswordControl)
        self.rpass_line.textChanged.connect(self.rpasswordControl)
        self.rrepass_line.textChanged.connect(self.rrepasswordControl)

        self.root_box.toggled.connect(self.lineEditsControl)
        self.host_line.textChanged.connect(self.lineEditsControl)
        self.name_line.textChanged.connect(self.lineEditsControl)
        self.user_line.textChanged.connect(self.lineEditsControl)
        self.pass_line.textChanged.connect(self.lineEditsControl)
        self.repass_line.textChanged.connect(self.lineEditsControl)
        self.rpass_line.textChanged.connect(self.lineEditsControl)
        self.rrepass_line.textChanged.connect(self.lineEditsControl)

        self.select_photo.clicked.connect(self.selectPhoto)
        self.take_photo.clicked.connect(self.takePhoto)
        self.retake_photo.clicked.connect(self.retakePhoto)
        self.parent.languageChanged.connect(self.retranslate)

        self.image_timer = QTimer(self)
        self.image_timer.timeout.connect(self.cameraView)

        self.retranslate()

    def retranslate(self):
        self.select_photo.setText(self.tr("Select Photo"))
        self.retake_photo.setText(self.tr("Retake Photo"))
        self.take_photo.setText(self.tr("Take Photo"))
        self.rrepass_line.setPlaceholderText(self.tr("Root Repassword"))
        self.rpass_line.setPlaceholderText(self.tr("Root Password"))
        self.root_box.setText(self.tr("Should the administrator and the user use the same password?"))
        self.auto_box.setText(self.tr("Sign in without password."))
        self.repass_line.setPlaceholderText(self.tr("Repassword"))
        self.pass_line.setPlaceholderText(self.tr("Password"))
        self.pass_label.setText(self.tr("Enter your user password."))
        self.host_line.setPlaceholderText(self.tr("Hostname"))
        self.host_label.setText(self.tr("What should this computer be named?"))
        self.user_line.setPlaceholderText(self.tr("Username"))
        self.user_label.setText(self.tr("Username to sign in?"))
        self.name_line.setPlaceholderText(self.tr("Fullname"))
        self.name_label.setText(self.tr("What is your name?"))
        self.setWindowTitle(self.tr("User Creation"))

    def showEvent(self, event):
        self.lineEditsControl()
        if len(self.cameras):
            self.retakePhoto()

    def autoControl(self):
        self.parent.lilii_settings["auto_login"] = self.auto_box.isChecked()

    def rootControl(self):
        self.parent.lilii_settings["root_user"] = self.root_box.isChecked()
        if not self.root_box.isChecked():
            self.rpass_line.show()
            self.rpass_icon.show()
            self.rrepass_line.show()
            self.rrepass_icon.show()
        else:
            self.rpass_line.hide()
            self.rpass_icon.hide()
            self.rrepass_line.hide()
            self.rrepass_icon.hide()

    def hostnameControl(self, hostname):
        if hostname.isalnum() and len(hostname) > 3:
            self.host_name = True
            self.host_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.host_name = False
            self.host_icon.setPixmap(QPixmap(":/images/xxx.svg"))

    def fullnameControl(self, fullname):
        if len(fullname) > 2:
            self.full_name = True
            self.name_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.full_name = False
            self.name_icon.setPixmap(QPixmap(":/images/xxx.svg"))

    def usernameControl(self, username):
        if username.isalnum() and len(username) > 3:
            self.user_name = True
            self.user_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.user_name = False
            self.user_icon.setPixmap(QPixmap(":/images/xxx.svg"))

    def fullnameToUsername(self, text):
        self.user_line.setText(text.lower().replace(" ", ""))

    def passwordControl(self, passwd):
        if len(passwd) > 5:
            self.passwd = True
            self.pass_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.passwd = False
            self.pass_icon.setPixmap(QPixmap(":/images/xxx.svg"))

        if passwd == self.repass_line.text():
            self.repasswd = True
            self.repass_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.repasswd = False
            self.repass_icon.setPixmap(QPixmap(":/images/xxx.svg"))

    def repasswordControl(self, repasswd):
        if repasswd == self.pass_line.text():
            self.repasswd = True
            self.repass_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.repasswd = False
            self.repass_icon.setPixmap(QPixmap(":/images/xxx.svg"))

    def rpasswordControl(self, passwd):
        if len(passwd) > 5:
            self.rpasswd = True
            self.rpass_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.rpasswd = False
            self.rpass_icon.setPixmap(QPixmap(":/images/xxx.svg"))

        if passwd == self.rrepass_line.text():
            self.rrepasswd = True
            self.rrepass_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.rrepasswd = False
            self.rrepass_icon.setPixmap(QPixmap(":/images/xxx.svg"))

    def rrepasswordControl(self, repasswd):
        if repasswd == self.rpass_line.text():
            self.rrepasswd = True
            self.rrepass_icon.setPixmap(QPixmap(":/images/apply.svg"))
        else:
            self.rrepasswd = False
            self.rrepass_icon.setPixmap(QPixmap(":/images/xxx.svg"))

    applyPage = pyqtSignal(bool)

    def lineEditsControl(self):
        if not self.root_box.isChecked():
            if self.host_name and self.full_name and self.user_name and self.passwd and self.repasswd and self.rpasswd \
                                                                                                    and self.rrepasswd:

                self.parent.lilii_settings["root_pass"] = self.rpass_line.text()
                self.applyPage.emit(True)

                self.parent.lilii_settings["fullname"] = self.name_line.text()
                self.parent.lilii_settings["username"] = self.user_line.text()
                self.parent.lilii_settings["password"] = self.pass_line.text()
                self.parent.lilii_settings["hostname"] = self.host_line.text()

            else:
                self.applyPage.emit(False)

        elif self.host_name and self.full_name and self.user_name and self.passwd and self.repasswd:
            self.parent.lilii_settings["fullname"] = self.name_line.text()
            self.parent.lilii_settings["username"] = self.user_line.text()
            self.parent.lilii_settings["password"] = self.pass_line.text()
            self.parent.lilii_settings["hostname"] = self.host_line.text()
            self.applyPage.emit(True)

        else:
            self.applyPage.emit(False)

    def selectPhoto(self):
        avatar_path = QDir.homePath() + "/.face.icon"
        file_path = QFileDialog.getOpenFileName(self, self.tr("Choose a user icon"), QDir.homePath(), "Image (*.png *.jpg)")

        if file_path[0]:
            image = Image.open(file_path[0])
            crop_image = image.crop(imageCrop(image))
            new_image = avatarCreate(crop_image)
            new_image.save(avatar_path, "PNG")
            self.photo_label.setPixmap(QPixmap(avatar_path))

            self.parent.lilii_settings["avatar"] = True

    def takePhoto(self):
        self.take_photo.hide()
        self.retake_photo.show()

        self.parent.lilii_settings["avatar"] = True
        self.image_timer.stop()
        self.camera.stop()

    def retakePhoto(self):
        self.retake_photo.hide()
        self.take_photo.show()
        self.camera.start()
        self.parent.lilii_settings["avatar"] = False
        self.image_timer.start(1000//30)

    def cameraView(self):
        self.image_capture.capture("/tmp/frame")

    def imageConvert(self, id, image):
        path = QDir.homePath() + "/.face.icon"
        im = Image.open(image)
        crop_image = im.crop(imageCrop(im))
        new_image = avatarCreate(crop_image)
        new_image.save(path, "PNG")
        self.photo_label.setPixmap(QPixmap.fromImage(ImageQt.ImageQt(new_image)))
示例#20
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
示例#21
0
class QmyCamerawindow(QMainWindow):
    def __initCamera(self):
        camInfo = QCameraInfo.defaultCamera()
        self.camera = QCamera(camInfo)
        self.camera2 = QCamera(camInfo)
        self.camera.setViewfinder(self._ui.widget)
        self.camera2.setViewfinder(self._ui.widget_2)
        self.camera.setCaptureMode(
            QCamera.CaptureStillImage)  #captureviewfinder
        self.camera2.setCaptureMode(QCamera.CaptureStillImage)

    def _initImageCapture(self):
        self.capture = QCameraImageCapture(self.camera)
        self.capture2 = QCameraImageCapture(self.camera2)
        setting = QImageEncoderSettings()
        setting.setCodec("image/jpeg")
        self.capture.setEncodingSettings(setting)
        self.capture.setBufferFormat(QVideoFrame.Format_Jpeg)
        self.capture.setCaptureDestination(QCameraImageCapture.CaptureToBuffer)
        self.capture.readyForCaptureChanged.connect(self.do_imageReady)
        self.capture.imageCaptured.connect(self.do_imageCaptured)
        self.capture2.setEncodingSettings(setting)
        self.capture2.setBufferFormat(QVideoFrame.Format_Jpeg)
        self.capture2.setCaptureDestination(
            QCameraImageCapture.CaptureToBuffer)
        self.capture2.readyForCaptureChanged.connect(self.do_imageReady)
        self.capture2.imageCaptured.connect(self.do_imageCaptured2)
        # self.capture.setCaptureDestination(QCameraImageCapture.CaptureToFile)
    def do_imageReady(self, ready):
        self._ui.actionActCaputure.setEnabled(ready)

    def do_imageCaptured2(self, image_id, preview):
        self.getpicname2()
        preview.save(self.picname2)
        cv2.waitKey(500)
        resultid = useract.find_one(self.facealbum_token, self.picname2)
        print(resultid)
        cv2.waitKey(500)
        data = sqlact.search_sql("student", resultid)
        print(data)
        self._ui.plainTextEdit_3.setPlainText(data[0][1])
        self._ui.plainTextEdit_4.setPlainText(data[0][2])
        self._ui.plainTextEdit_5.setPlainText(str(data[0][3]))
        # print(preview)
    def do_imageCaptured(self, image_id, preview):
        H = self._ui.label_2.height()
        W = self._ui.label_2.width()
        scaledImage = preview.scaled(W, H, Qt.KeepAspectRatio,
                                     Qt.SmoothTransformation)
        self._ui.label_2.setPixmap(QPixmap.fromImage(scaledImage))
        self.getpicname()
        preview.save(self.picname)

        # useract.add_newone("student",name)

    def on_actionActCaputure_triggered(self):
        # QSound.play("shutter.wav")
        self.camera.searchAndLock()
        self.capture.capture()
        self.camera.unlock()
        # FName = fr"E:\iddatabasepic\cap{time.strftime('%Y%m%d%H%M%S', time.localtime())}"
        # self.flag += 1
        # self.capture.capture(FName)
        # print(f"捕获图像保存到文件:{FName}.jpg")

    def on_actionActStartCamera_triggered(self):
        self.camera.start()
        self.flag = 1

    def on_actionActCloseCamrera_triggered(self):
        self.camera.stop()
        self.flag = 0

    def on_actionActExit_triggered(self):
        self.camera.stop()
        self.close()

    def gettext(self):
        self.text = self._ui.plainTextEdit.toPlainText()
        self.text2 = self._ui.plainTextEdit_2.toPlainText()
        useract.add_newone("student", self.text, self.text2,
                           self.facealbum_token, self.picname)

    def getpicname(self):  #获取图片名
        self.picname = fr"E:\iddatabasepic\cap{time.strftime('%Y%m%d%H%M%S', time.localtime())}" + ".jpg"

        # print(self.text)
    def getpicname2(self):  #获取图片名
        self.picname2 = fr"E:\iddatabasepic\capnew{time.strftime('%Y%m%d%H%M%S', time.localtime())}" + ".jpg"

    def tabshift1(self):
        # print(self.tabWidget.currentIndex())
        # print("hello")
        self._ui.tabWidget.setCurrentIndex(0)
        if self.flag2 == 1:
            self.camera2.stop()
            self.flag2 = 0

    def tabshift2(self):
        self._ui.tabWidget.setCurrentIndex(1)
        if self.flag == 1:
            self.camera.stop()
            self.flag = 0
        self.flag2 = 1
        useract.group_all(self.facealbum_token)
        self.camera2.start()

    def tabshift3(self):
        self._ui.tabWidget.setCurrentIndex(2)
        if self.flag == 1:
            self.camera.stop()
            self.flag = 0
        if self.flag2 == 1:
            self.camera2.stop()
            self.flag2 = 0

    def searchcap(self):
        self.camera2.searchAndLock()
        self.capture2.capture()
        self.camera2.unlock()

    def dataview(self):
        view = sqlact.search_all_sql("student")
        self._ui.plainTextEdit_7.setPlainText(",".join(
            [str(t) for i in view for t in i]))

    def __init__(self, parent=None):
        super().__init__(parent)
        self._ui = Ui_MainWindowcamera()
        self.flag = 1
        self.flag2 = 0
        self._ui.setupUi(self)
        self.camera = None
        self.picname2 = ""
        self.picname = ""
        self.facealbum_token = "1577420387-3990379c-dcc2-4fe8-ae47-bf37a299118d"
        self._ui.btnget.clicked.connect(self.gettext)
        self._ui.addnew.clicked.connect(self.tabshift1)
        self._ui.searchinfo.clicked.connect(self.tabshift2)
        self._ui.pushButton_3.clicked.connect(self.tabshift3)
        self._ui.btncap.clicked.connect(self.searchcap)
        self._ui.btndata.clicked.connect(self.dataview)
        cameras = QCameraInfo.availableCameras()
        if len(cameras) > 0:
            self.__initCamera()
            self._initImageCapture()
            self.camera.start()
示例#22
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
示例#23
0
class TIFgrabGUI(QMainWindow):
    def __init__(self, capcard_full, capcard_short, parent=None):
        super(TIFgrabGUI, self).__init__(parent)

        self.cleanup_side_captures()

        # set up GUI from designer-made layout
        self.ui = Ui_TIFgrabMW()
        self.ui.setupUi(self)

        # Temporarily? hard code the device definition
        self.sys_device = "/dev/video0"
        target_cam_serialnum = capcard_short[self.sys_device]
        target_cam_label = capcard_full[self.sys_device]

        print("Targeting camera device ", self.sys_device)
        print("Labeling as ", target_cam_label)

        self.picframe_width = self.ui.ThumbnailView.frameGeometry().width()
        self.picframe_height = self.ui.ThumbnailView.frameGeometry().height()

        #for device_name in QCamera.availableDevices():
        #    print("Looking at", device_name)
        #    if (device_name == target_cam_dev):
        #self.camera_device = device_name
        #        self.camera_device = target_cam_dev.encode('utf-8')
        self.camera_device = self.sys_device.encode('utf-8')
        self.camera_label = target_cam_label
        self.ui.Sourcename_Disp.setText(self.camera_label)
        self.cam1 = QCamera(self.camera_device)

        #        self.cam1_info = QCameraInfo(self.cam1)
        #        self.cam1_nonhuman_name = self.cam1_info.deviceName()
        #        print("Description= ",self.cam1_info.description())
        #        print("Nonhuman= ", self.cam1_info.deviceName())

        self.cam1_capture = QCameraImageCapture(self.cam1)
        print("Still image capture from device %s, capture card %s)" %
              (self.camera_device, self.camera_label))

        self.cam1.setCaptureMode(QCamera.CaptureStillImage)
        self.cam1_capture.setCaptureDestination(
            QCameraImageCapture.CaptureToBuffer)

        #### Assign a startup image ####
        # print('Displaying startup image')
        #self.tifimage = QPixmap('/home/scotty/src/GrabDev/tasman_island_lighthouse.tif', 'tif')
        self.tifimage = QPixmap('./tasman_island_lighthouse.tif', 'tif')
        self.thumb = self.tifimage.scaled(self.picframe_width,
                                          self.picframe_height,
                                          Qt.KeepAspectRatio)
        self.ui.ThumbnailView.setScaledContents(True)
        self.ui.ThumbnailView.setPixmap(self.thumb)

        # Set event handlers
        self.ui.grabButton.clicked.connect(self.on_grab_button)
        self.ui.TimerRadio.toggled.connect(self.on_timerradio_button)
        self.ui.quitButton.clicked.connect(self.on_quit_button)
        self.cam1_capture.imageCaptured.connect(self.on_image_captured)

        self.ui.FilenameDisp.setText("No image captured")
        self.cam1.start()

    def on_grab_button(self):
        self.cam1.searchAndLock()
        self.capture_time = systime()
        self.capture_name = "./" + self.camera_label + "_" + self.capture_time + ".tif"
        self.cam1_capture.capture()
        self.cam1.unlock()

    def on_image_captured(self, id, captured_image):
        # The image to be displayed on screen
        self.captured2pixmap = QPixmap()
        success = self.captured2pixmap.convertFromImage(captured_image)

        self.list_pic_stats()

        self.thumb_scaled = self.captured2pixmap.scaled(
            self.picframe_width, self.picframe_height, Qt.KeepAspectRatio)
        self.ui.ThumbnailView.setScaledContents(True)
        self.ui.ThumbnailView.setSizePolicy(QSizePolicy.Ignored,
                                            QSizePolicy.Ignored)
        self.ui.FilenameDisp.setText(self.capture_name)
        self.ui.ThumbnailView.setPixmap(self.thumb_scaled)

        # The image to be saved to file as TIF
        # First confirm that the destination folder exists, create if it doesn't.
        self.manage_daily_folder()
        self.capture_fullpath = self.outdirname + "/" + self.capture_name
        outimage = QPixmap()
        outimage.convertFromImage(captured_image)
        outfile = QFile(self.capture_fullpath)
        outfile.open(QIODevice.WriteOnly)
        outimage.save(outfile, "TIFF")
        outfile.close()

    def list_pic_stats(self):

        sizestr = ("Size: %d X %d") % (self.captured2pixmap.width(),
                                       self.captured2pixmap.height())
        depthstr = ("Depth:%s ") % (self.captured2pixmap.depth())
        bmapstr = ("Is Bitmap?:%s") % (self.captured2pixmap.isQBitmap())
        alphastr = ("Has alpha?:%s") % (self.captured2pixmap.hasAlphaChannel())
        self.ui.PicStats.setPlainText(self.sys_device)
        self.ui.PicStats.appendPlainText(sizestr)
        self.ui.PicStats.appendPlainText(depthstr)

    def on_timerradio_button(self):
        if self.ui.TimerRadio.isChecked():
            self.ui.grabButton.setEnabled(False)
            self.add_timer_groupbox()
        if not self.ui.TimerRadio.isChecked():
            if self.timergb:
                self.timergb.grab_timer.stop()
                self.ui.grabButton.setEnabled(True)
                self.timergb.deleteLater()
                self.timergb = None

    def add_timer_groupbox(self):

        self.timergb = TimerGB(75, 100)
        self.timergb.grab_timeout.connect(self.on_grab_button)
        self.timergb.gb_closed.connect(self.on_timergb_closed)
        self.timergb.show()

    def on_timergb_closed(self):
        if self.ui.TimerRadio.isChecked():
            if self.timergb:
                #     self.grab_timer.stop()
                self.timergb.deleteLater()
                self.timergb = None
                self.ui.TimerRadio.setChecked(False)
                self.ui.grabButton.setEnabled(True)

    def cleanup_side_captures(self):
        # Remove jpgs saved by QCameraImageCapture in default location
        defaultlocation = "/home/jason/Pictures"
        print("Removing all jpgs from ", defaultlocation)
        fullpath = ("%s/*.jpg") % (defaultlocation)
        for filename in glob(fullpath):
            print("Removing ", filename)
            os.remove(filename)

    def on_quit_button(self):
        self.cam1.stop()
        try:
            if self.timergb:
                self.timergb.deleteLater()
                self.timergb = None
        except:
            pass

        self.cleanup_side_captures()

        QCoreApplication.exit()

    def sigint_handler(*args):
        try:
            if self.timergb:
                self.timergb.deleteLater()
                self.timergb = None
        except:
            pass
        sys.stderr.write('\r')
        QApplication.quit()

    def do_init(ini_filename):
        cf = ConfigParser()
        cf.read(ini_filename)

    def manage_daily_folder(self):
        # Tests for existence of folder to hold the date's captures.
        # If folder doesn't exist, creates it.
        today = sysdate()

        self.outdirname = "/data/capture_" + today
        if not os.path.exists(self.outdirname):
            os.makedirs(self.outdirname)
示例#24
0
class Camera(QMainWindow):
    def __init__(self, parent=None):
        super(Camera, self).__init__(parent)

        self.ui = Ui_Camera()
        self.camera = None
        self.imageCapture = None
        self.mediaRecorder = None
        self.isCapturingImage = False
        self.applicationExiting = False

        self.imageSettings = QImageEncoderSettings()
        self.audioSettings = QAudioEncoderSettings()
        self.videoSettings = QVideoEncoderSettings()
        self.videoContainerFormat = ''

        self.ui.setupUi(self)

        cameraDevice = QByteArray()

        videoDevicesGroup = QActionGroup(self)
        videoDevicesGroup.setExclusive(True)

        for deviceName in QCamera.availableDevices():
            description = QCamera.deviceDescription(deviceName)
            videoDeviceAction = QAction(description, videoDevicesGroup)
            videoDeviceAction.setCheckable(True)
            videoDeviceAction.setData(deviceName)

            if cameraDevice.isEmpty():
                cameraDevice = deviceName
                videoDeviceAction.setChecked(True)

            self.ui.menuDevices.addAction(videoDeviceAction)

        videoDevicesGroup.triggered.connect(self.updateCameraDevice)
        self.ui.captureWidget.currentChanged.connect(self.updateCaptureMode)

        self.ui.lockButton.hide()

        self.setCamera(cameraDevice)

    def setCamera(self, cameraDevice):
        if cameraDevice.isEmpty():
            self.camera = QCamera()
        else:
            self.camera = QCamera(cameraDevice)

        self.camera.stateChanged.connect(self.updateCameraState)
        self.camera.error.connect(self.displayCameraError)

        self.mediaRecorder = QMediaRecorder(self.camera)
        self.mediaRecorder.stateChanged.connect(self.updateRecorderState)

        self.imageCapture = QCameraImageCapture(self.camera)

        self.mediaRecorder.durationChanged.connect(self.updateRecordTime)
        self.mediaRecorder.error.connect(self.displayRecorderError)

        self.mediaRecorder.setMetaData(QMediaMetaData.Title, "Test Title")

        self.ui.exposureCompensation.valueChanged.connect(
            self.setExposureCompensation)

        self.camera.setViewfinder(self.ui.viewfinder)

        self.updateCameraState(self.camera.state())
        self.updateLockStatus(self.camera.lockStatus(), QCamera.UserRequest)
        self.updateRecorderState(self.mediaRecorder.state())

        self.imageCapture.readyForCaptureChanged.connect(self.readyForCapture)
        self.imageCapture.imageCaptured.connect(self.processCapturedImage)
        self.imageCapture.imageSaved.connect(self.imageSaved)

        self.camera.lockStatusChanged.connect(self.updateLockStatus)

        self.ui.captureWidget.setTabEnabled(
            0, self.camera.isCaptureModeSupported(QCamera.CaptureStillImage))
        self.ui.captureWidget.setTabEnabled(
            1, self.camera.isCaptureModeSupported(QCamera.CaptureVideo))

        self.updateCaptureMode()
        self.camera.start()

    def keyPressEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_CameraFocus:
            self.displayViewfinder()
            self.camera.searchAndLock()
            event.accept()
        elif event.key() == Qt.Key_Camera:
            if self.camera.captureMode() == QCamera.CaptureStillImage:
                self.takeImage()
            elif self.mediaRecorder.state() == QMediaRecorder.RecordingState:
                self.stop()
            else:
                self.record()

            event.accept()
        else:
            super(Camera, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_CameraFocus:
            self.camera.unlock()
        else:
            super(Camera, self).keyReleaseEvent(event)

    def updateRecordTime(self):
        msg = "Recorded %d sec" % (self.mediaRecorder.duration() // 1000)
        self.ui.statusbar.showMessage(msg)

###############################################################################

    def detectChars(self, qImg):
        incomingImage = qImg.convertToFormat(4)

        width = incomingImage.width()
        height = incomingImage.height()

        ptr = incomingImage.bits()
        ptr.setsize(incomingImage.byteCount())
        cvImg = np.array(ptr).reshape(height, width, 4)  # Copies the data
        ######################
        centerx = int(cvImg.shape[1] / 2)
        centery = int(cvImg.shape[0] / 2)
        half_width = 200
        half_height = 100
        y = centery - half_height
        x = centerx - half_width
        print(type(cvImg))
        cvImgCroped = cvImg[y:y + half_height * 2, x:x + half_width *
                            2]  # Crop from x, y, w, h -> 100, 200, 300, 400
        cvImgCContinues = np.zeros(cvImgCroped.shape, np.uint8)
        cvImgCContinues = cvImgCroped.copy()
        # NOTE: its img[y: y + h, x: x + w] and *not* img[x: x + w, y: y + h]
        # cvImgCroped = cv2.rectangle(cvImgCroped,
        #               (centerx - half_width, centery - half_height),
        #               (centerx + half_width, centery + half_height),
        #               (0, 0, 255),
        #               2)

        ######################

        # Convert to RGB for QImage.
        cvImgCContinues = cv2.cvtColor(cvImgCContinues, cv2.COLOR_BGR2RGB)
        # cv2.imshow("",cvImgCContinues)
        # cv2.waitKey(0)
        height, width, bytesPerComponent = cvImgCContinues.shape
        bytesPerLine = bytesPerComponent * width
        self.image = QImage(cvImgCContinues.data, width, height, bytesPerLine,
                            QImage.Format_RGB888)
        return self.image

###############################################################################

    def processCapturedImage(self, requestId, img):
        detectedImage = self.detectChars(img)
        scaledImage = detectedImage.scaled(self.ui.viewfinder.size(),
                                           Qt.KeepAspectRatio,
                                           Qt.SmoothTransformation)
        self.ui.lastImagePreviewLabel.setPixmap(QPixmap.fromImage(scaledImage))

        self.displayCapturedImage()
        QTimer.singleShot(40000, self.displayViewfinder)


###############################################################################

    def configureCaptureSettings(self):
        if self.camera.captureMode() == QCamera.CaptureStillImage:
            self.configureImageSettings()
        elif self.camera.captureMode() == QCamera.CaptureVideo:
            self.configureVideoSettings()

    def configureVideoSettings(self):
        settingsDialog = VideoSettings(self.mediaRecorder)

        settingsDialog.setAudioSettings(self.audioSettings)
        settingsDialog.setVideoSettings(self.videoSettings)
        settingsDialog.setFormat(self.videoContainerFormat)

        if settingsDialog.exec_():
            self.audioSettings = settingsDialog.audioSettings()
            self.videoSettings = settingsDialog.videoSettings()
            self.videoContainerFormat = settingsDialog.format()

            self.mediaRecorder.setEncodingSettings(self.audioSettings,
                                                   self.videoSettings,
                                                   self.videoContainerFormat)

    def configureImageSettings(self):
        settingsDialog = ImageSettings(self.imageCapture)

        settingsDialog.setImageSettings(self.imageSettings)

        if settingsDialog.exec_():
            self.imageSettings = settingsDialog.imageSettings()
            self.imageCapture.setEncodingSettings(self.imageSettings)

    def record(self):
        self.mediaRecorder.record()
        self.updateRecordTime()

    def pause(self):
        self.mediaRecorder.pause()

    def stop(self):
        self.mediaRecorder.stop()

    def setMuted(self, muted):
        self.mediaRecorder.setMuted(muted)

    def toggleLock(self):
        if self.camera.lockStatus() in (QCamera.Searching, QCamera.Locked):
            self.camera.unlock()
        elif self.camera.lockStatus() == QCamera.Unlocked:
            self.camera.searchAndLock()

    def updateLockStatus(self, status, reason):
        indicationColor = Qt.black

        if status == QCamera.Searching:
            self.ui.statusbar.showMessage("Focusing...")
            self.ui.lockButton.setText("Focusing...")
            indicationColor = Qt.yellow
        elif status == QCamera.Locked:
            self.ui.lockButton.setText("Unlock")
            self.ui.statusbar.showMessage("Focused", 2000)
            indicationColor = Qt.darkGreen
        elif status == QCamera.Unlocked:
            self.ui.lockButton.setText("Focus")

            if reason == QCamera.LockFailed:
                self.ui.statusbar.showMessage("Focus Failed", 2000)
                indicationColor = Qt.red

        palette = self.ui.lockButton.palette()
        palette.setColor(QPalette.ButtonText, indicationColor)
        self.ui.lockButton.setPalette(palette)

    def takeImage(self):
        self.isCapturingImage = True
        self.imageCapture.capture()

    def startCamera(self):
        self.camera.start()

    def stopCamera(self):
        self.camera.stop()

    def updateCaptureMode(self):
        tabIndex = self.ui.captureWidget.currentIndex()
        captureMode = QCamera.CaptureStillImage if tabIndex == 0 else QCamera.CaptureVideo

        if self.camera.isCaptureModeSupported(captureMode):
            self.camera.setCaptureMode(captureMode)

    def updateCameraState(self, state):
        if state == QCamera.ActiveState:
            self.ui.actionStartCamera.setEnabled(False)
            self.ui.actionStopCamera.setEnabled(True)
            self.ui.captureWidget.setEnabled(True)
            self.ui.actionSettings.setEnabled(True)
        elif state in (QCamera.UnloadedState, QCamera.LoadedState):
            self.ui.actionStartCamera.setEnabled(True)
            self.ui.actionStopCamera.setEnabled(False)
            self.ui.captureWidget.setEnabled(False)
            self.ui.actionSettings.setEnabled(False)

    def updateRecorderState(self, state):
        if state == QMediaRecorder.StoppedState:
            self.ui.recordButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(True)
            self.ui.stopButton.setEnabled(False)
        elif state == QMediaRecorder.PausedState:
            self.ui.recordButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(False)
            self.ui.stopButton.setEnabled(True)
        elif state == QMediaRecorder.RecordingState:
            self.ui.recordButton.setEnabled(False)
            self.ui.pauseButton.setEnabled(True)
            self.ui.stopButton.setEnabled(True)

    def setExposureCompensation(self, index):
        self.camera.exposure().setExposureCompensation(index * 0.5)

    def displayRecorderError(self):
        QMessageBox.warning(self, "Capture error",
                            self.mediaRecorder.errorString())

    def displayCameraError(self):
        QMessageBox.warning(self, "Camera error", self.camera.errorString())

    def updateCameraDevice(self, action):
        self.setCamera(action.data())

    def displayViewfinder(self):
        self.ui.stackedWidget.setCurrentIndex(0)

    def displayCapturedImage(self):
        self.ui.stackedWidget.setCurrentIndex(1)

    def readyForCapture(self, ready):
        self.ui.takeImageButton.setEnabled(ready)

    def imageSaved(self, id, fileName):
        self.isCapturingImage = False

        if self.applicationExiting:
            self.close()

    def closeEvent(self, event):
        if self.isCapturingImage:
            self.setEnabled(False)
            self.applicationExiting = True
            event.ignore()
        else:
            event.accept()
示例#25
0
class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)  #调用父类构造函数,创建窗体
        self.ui = Ui_MainWindow()  #创建UI对象
        self.ui.setupUi(self)  #构造UI界面

        self.__LabCameraState = QLabel("摄像头state:")
        self.__LabCameraState.setMinimumWidth(150)
        self.ui.statusBar.addWidget(self.__LabCameraState)

        self.__LabImageID = QLabel("图片文件ID:")
        self.__LabImageID.setMinimumWidth(100)
        self.ui.statusBar.addWidget(self.__LabImageID)

        self.__LabImageFile = QLabel("")  #保存的图片文件名
        ##      self.ui.statusBar.addWidget(self.__LabImageFile)
        self.ui.statusBar.addPermanentWidget(self.__LabImageFile)

        self.camera = None  #QCamera对象
        cameras = QCameraInfo.availableCameras()  #list[QCameraInfo]
        if len(cameras) > 0:
            self.__iniCamera()  #初始化摄像头
            self.__iniImageCapture()  #初始化静态画图
            self.camera.start()

##  ==============自定义功能函数========================

    def __iniCamera(self):  ##创建 QCamera对象
        camInfo = QCameraInfo.defaultCamera()  #获取缺省摄像头,QCameraInfo
        self.ui.comboCamera.addItem(camInfo.description())  #摄像头描述
        self.ui.comboCamera.setCurrentIndex(0)

        self.camera = QCamera(camInfo)  #创建摄像头对象
        self.camera.setViewfinder(self.ui.viewFinder)  #设置取景框预览
        ##          camera.setCaptureMode(QCamera.CaptureViewfinder) #预览
        self.camera.setCaptureMode(QCamera.CaptureStillImage)  #设置为抓图
        ##          camera.setCaptureMode(QCamera.CaptureVideo)

        mode = QCamera.CaptureStillImage
        supported = self.camera.isCaptureModeSupported(mode)
        self.ui.checkStillImage.setChecked(supported)  #支持拍照

        supported = self.camera.isCaptureModeSupported(QCamera.CaptureVideo)
        self.ui.checkVideo.setChecked(supported)  #支持视频录制

        supported = self.camera.exposure().isAvailable()
        self.ui.checkExposure.setChecked(supported)  #支持曝光补偿

        supported = self.camera.focus().isAvailable()
        self.ui.checkFocus.setChecked(supported)  #支持变焦

        self.camera.stateChanged.connect(self.do_cameraStateChanged)

    def __iniImageCapture(self):  ##创建 QCameraImageCapture对象
        self.capturer = QCameraImageCapture(self.camera)
        settings = QImageEncoderSettings()  #拍照设置
        settings.setCodec("image/jpeg")  #设置抓图图形编码
        settings.setResolution(640, 480)  #分辨率
        settings.setQuality(QMultimedia.HighQuality)  #图片质量
        self.capturer.setEncodingSettings(settings)

        self.capturer.setBufferFormat(QVideoFrame.Format_Jpeg)  #缓冲区格式

        if self.ui.chkBoxSaveToFile.isChecked():
            dest = QCameraImageCapture.CaptureToFile  #保存到文件
        else:
            dest = QCameraImageCapture.CaptureToBuffer  #保存到缓冲区
        self.capturer.setCaptureDestination(dest)  #保存目标

        self.capturer.readyForCaptureChanged.connect(self.do_imageReady)

        self.capturer.imageCaptured.connect(self.do_imageCaptured)

        self.capturer.imageSaved.connect(self.do_imageSaved)

##  ==============event处理函数==========================

##  ==========由connectSlotsByName()自动连接的槽函数============

    @pyqtSlot(bool)  ##设置保存方式
    def on_chkBoxSaveToFile_clicked(self, checked):
        if checked:
            dest = QCameraImageCapture.CaptureToFile  #保存到文件
        else:
            dest = QCameraImageCapture.CaptureToBuffer  #保存到缓冲区
        self.capturer.setCaptureDestination(dest)  #保存目标

    @pyqtSlot()  ##拍照
    def on_actCapture_triggered(self):
        QSound.play("shutter.wav")  #播放快门音效
        self.camera.searchAndLock()  #快门半按下时锁定摄像头参数
        self.capturer.capture()  #拍照
        self.camera.unlock()  #快门按钮释放时解除锁定

    @pyqtSlot()  ##打开摄像头
    def on_actStartCamera_triggered(self):
        self.camera.start()

    @pyqtSlot()  ##关闭摄像头
    def on_actStopCamera_triggered(self):
        self.camera.stop()

    ##  =============自定义槽函数===============================
    def do_cameraStateChanged(self, state):  ##摄像头状态变化
        if (state == QCamera.UnloadedState):
            self.__LabCameraState.setText("摄像头state: UnloadedState")
        elif (state == QCamera.LoadedState):
            self.__LabCameraState.setText("摄像头state: LoadedState")
        elif (state == QCamera.ActiveState):
            self.__LabCameraState.setText("摄像头state: ActiveState")

        self.ui.actStartCamera.setEnabled(state != QCamera.ActiveState)
        self.ui.actStopCamera.setEnabled(state == QCamera.ActiveState)

    def do_imageReady(self, ready):  ##是否可以拍照了
        self.ui.actCapture.setEnabled(ready)

    def do_imageCaptured(self, imageID, preview):  ##图片被抓取到内存
        #preview是 QImage
        H = self.ui.LabImage.height()
        W = self.ui.LabImage.width()

        scaledImage = preview.scaled(W, H, Qt.KeepAspectRatio,
                                     Qt.SmoothTransformation)
        self.ui.LabImage.setPixmap(QPixmap.fromImage(scaledImage))
        self.__LabImageID.setText("图片文件ID:%d" % imageID)
        self.__LabImageFile.setText("图片保存为: ")

    def do_imageSaved(self, imageID, fileName):  ##图片被保存
        self.__LabImageID.setText("图片文件ID:%d" % imageID)
        self.__LabImageFile.setText("图片保存为: " + fileName)
示例#26
0
class FaceRegistrationView(QDialog):
  def __init__(self, parent=None, face_recognizer=None):
    QDialog.__init__(self, parent=parent)
    self.face_recognizer = face_recognizer
    self.ui = Ui_FaceRegistrationUI()

    self.ui.setupUi(self)

    # Add existing face albums to the combobox
    # FIXME: need to get this list from the face recognizer
    for registry in self.face_recognizer.list_face_registries():
      self.ui.registryNameSelect.addItem(registry)

    self.ui.retakeButton.setEnabled(False)
    self.cur_face_name = None
    self.cur_face_registry = self.ui.registryNameSelect.currentText()
    self.camera = None
    self.image_capture = None
    self.cur_saved_image_path = None
    self.setup_camera()

  def setup_camera(self):
    camera_device = QByteArray()

    for device in QCamera.availableDevices():
      if camera_device.isEmpty():
        camera_device = device
    if camera_device.isEmpty():
      self.camera = QCamera()
    else:
      self.camera = QCamera(camera_device)

    self.image_capture = QCameraImageCapture(self.camera)
    self.image_capture.readyForCaptureChanged.connect(self.ready_for_capture)
    self.image_capture.imageCaptured.connect(self.process_captured_image)
    self.image_capture.imageSaved.connect(self.image_saved)

    self.camera.setViewfinder(self.ui.viewFinder)
    self.camera.start()

  def ready_for_capture(self, ready):
    self.ui.captureButton.setEnabled(ready)

  def process_captured_image(self, request_id, image):
    scaled_image = image.scaled(self.ui.viewFinder.size(),
                                Qt.KeepAspectRatio, Qt.SmoothTransformation)
    self.ui.picturePreview.setPixmap(QPixmap.fromImage(scaled_image))
    self.show_captured_image()

  def image_saved(self, id, file_path):
    self.cur_saved_image_path = file_path
    logger.info('Image saved at {}'.format(file_path))

  def handle_face_name(self, name):
    self.cur_face_name = name

  def register_face(self):
    name = self.ui.nameInput.text()
    if name == '':
      msg_box = QMessageBox()
      msg_box.setIcon(QMessageBox.Critical)
      msg_box.warning(self, 'Error', 'Person name cannot be empty!')
      return

    confirm_msg = 'Register face of {:s} into {:s}?'.format(name,
                                                           self.cur_face_registry)
    reply = QMessageBox.question(self, 'Register face', confirm_msg,
                                   QMessageBox.No, QMessageBox.Yes)
    if reply == QMessageBox.Yes:
      logger.info('Registering {:s}'.format(name))
      try:
        self.face_recognizer.register_face(self.cur_face_registry,
                                           self.cur_saved_image_path, name)
        self.parent().ui.statusbar.showMessage(
          'Successfully registered the face', 2000)

      except Exception as e:
        msg_box = QMessageBox()
        msg_box.setIcon(QMessageBox.Critical)
        msg_box.warning(self, 'Error', str(e))
      # Clean up the captured image and show the video stream again
      self.ui.nameInput.clear()
      # self.ui.nameInput.setText('')
      self.retake_picture()
    else:
      pass

  def retake_picture(self):

    self.delete_current_picture()
    self.ui.captureButton.setEnabled(True)
    self.ui.retakeButton.setEnabled(False)
    self.show_video_stream()

  def capture_picture(self):
    self.image_capture.capture()
    self.ui.captureButton.setEnabled(False)
    self.ui.retakeButton.setEnabled(True)

  def show_captured_image(self):
    self.ui.stackedWidget.setCurrentIndex(1)

  def show_video_stream(self):
    self.ui.stackedWidget.setCurrentIndex(0)

  def set_current_face_registry(self, registry_name):
    self.cur_face_registry = registry_name

  def closeEvent(self, event):
    self.camera.stop()
    self.delete_current_picture()

  def accept(self):
    self.camera.stop()
    self.delete_current_picture()
    QDialog.reject(self)

  def reject(self):
    self.camera.stop()
    logger.info('Cleaning up captured images...')
    self.delete_current_picture()
    QDialog.reject(self)

  def delete_current_picture(self):
    if self.cur_saved_image_path is not None:
      if os.path.exists(self.cur_saved_image_path):
        os.remove(self.cur_saved_image_path)
        logger.info('Deleted {}'.format(self.cur_saved_image_path))
      self.cur_saved_image_path = None
示例#27
0
class Camera(QMainWindow):

    def __init__(self, parent=None):
        super(Camera, self).__init__(parent)

        self.ui = Ui_Camera()
        self.camera = None
        self.imageCapture = None
        self.mediaRecorder = None
        self.isCapturingImage = False
        self.applicationExiting = False

        self.imageSettings = QImageEncoderSettings()
        self.audioSettings = QAudioEncoderSettings()
        self.videoSettings = QVideoEncoderSettings()
        self.videoContainerFormat = ''

        self.ui.setupUi(self)

        cameraDevice = QByteArray()

        videoDevicesGroup = QActionGroup(self)
        videoDevicesGroup.setExclusive(True)

        for deviceName in QCamera.availableDevices():
            description = QCamera.deviceDescription(deviceName)
            videoDeviceAction = QAction(description, videoDevicesGroup)
            videoDeviceAction.setCheckable(True)
            videoDeviceAction.setData(deviceName)

            if cameraDevice.isEmpty():
                cameraDevice = deviceName
                videoDeviceAction.setChecked(True)

            self.ui.menuDevices.addAction(videoDeviceAction)

        videoDevicesGroup.triggered.connect(self.updateCameraDevice)
        self.ui.captureWidget.currentChanged.connect(self.updateCaptureMode)

        self.ui.lockButton.hide()

        self.setCamera(cameraDevice)

    def setCamera(self, cameraDevice):
        if cameraDevice.isEmpty():
            self.camera = QCamera()
        else:
            self.camera = QCamera(cameraDevice)

        self.camera.stateChanged.connect(self.updateCameraState)
        self.camera.error.connect(self.displayCameraError)

        self.mediaRecorder = QMediaRecorder(self.camera)
        self.mediaRecorder.stateChanged.connect(self.updateRecorderState)

        self.imageCapture = QCameraImageCapture(self.camera)

        self.mediaRecorder.durationChanged.connect(self.updateRecordTime)
        self.mediaRecorder.error.connect(self.displayRecorderError)

        self.mediaRecorder.setMetaData(QMediaMetaData.Title, "Test Title")

        self.ui.exposureCompensation.valueChanged.connect(
                self.setExposureCompensation)

        self.camera.setViewfinder(self.ui.viewfinder)

        self.updateCameraState(self.camera.state())
        self.updateLockStatus(self.camera.lockStatus(), QCamera.UserRequest)
        self.updateRecorderState(self.mediaRecorder.state())

        self.imageCapture.readyForCaptureChanged.connect(self.readyForCapture)
        self.imageCapture.imageCaptured.connect(self.processCapturedImage)
        self.imageCapture.imageSaved.connect(self.imageSaved)

        self.camera.lockStatusChanged.connect(self.updateLockStatus)

        self.ui.captureWidget.setTabEnabled(0,
                self.camera.isCaptureModeSupported(QCamera.CaptureStillImage))
        self.ui.captureWidget.setTabEnabled(1,
                self.camera.isCaptureModeSupported(QCamera.CaptureVideo))

        self.updateCaptureMode()
        self.camera.start()

    def keyPressEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_CameraFocus:
            self.displayViewfinder()
            self.camera.searchAndLock()
            event.accept()
        elif event.key() == Qt.Key_Camera:
            if self.camera.captureMode() == QCamera.CaptureStillImage:
                self.takeImage()
            elif self.mediaRecorder.state() == QMediaRecorder.RecordingState:
                self.stop()
            else:
                self.record()

            event.accept()
        else:
            super(Camera, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_CameraFocus:
            self.camera.unlock()
        else:
            super(Camera, self).keyReleaseEvent(event)

    def updateRecordTime(self):
        msg = "Recorded %d sec" % self.mediaRecorder.duration() // 1000
        self.ui.statusbar.showMessage(msg)

    def processCapturedImage(self, requestId, img):
        scaledImage = img.scaled(self.ui.viewfinder.size(), Qt.KeepAspectRatio,
                Qt.SmoothTransformation)

        self.ui.lastImagePreviewLabel.setPixmap(QPixmap.fromImage(scaledImage))

        self.displayCapturedImage()
        QTimer.singleShot(4000, self.displayViewfinder)

    def configureCaptureSettings(self):
        if self.camera.captureMode() == QCamera.CaptureStillImage:
            self.configureImageSettings()
        elif self.camera.captureMode() == QCamera.CaptureVideo:
            self.configureVideoSettings()

    def configureVideoSettings(self):
        settingsDialog = VideoSettings(self.mediaRecorder)

        settingsDialog.setAudioSettings(self.audioSettings)
        settingsDialog.setVideoSettings(self.videoSettings)
        settingsDialog.setFormat(self.videoContainerFormat)

        if settingsDialog.exec_():
            self.audioSettings = settingsDialog.audioSettings()
            self.videoSettings = settingsDialog.videoSettings()
            self.videoContainerFormat = settingsDialog.format()

            self.mediaRecorder.setEncodingSettings(self.audioSettings,
                    self.videoSettings, self.videoContainerFormat)

    def configureImageSettings(self):
        settingsDialog = ImageSettings(self.imageCapture)

        settingsDialog.setImageSettings(self.imageSettings)

        if settingsDialog.exec_():
            self.imageSettings = settingsDialog.imageSettings()
            imageCapture.setEncodingSettings(self.imageSettings)

    def record(self):
        self.mediaRecorder.record()
        self.updateRecordTime()

    def pause(self):
        self.mediaRecorder.pause()

    def stop(self):
        self.mediaRecorder.stop()

    def setMuted(self, muted):
        self.mediaRecorder.setMuted(muted)

    def toggleLock(self):
        if self.camera.lockStatus() in (QCamera.Searching, QCamera.Locked):
            self.camera.unlock()
        elif self.camera.lockStatus() == QCamera.Unlocked:
            self.camera.searchAndLock()

    def updateLockStatus(self, status, reason):
        indicationColor = Qt.black

        if status == QCamera.Searching:
            self.ui.statusbar.showMessage("Focusing...")
            self.ui.lockButton.setText("Focusing...")
            indicationColor = Qt.yellow
        elif status == QCamera.Locked:
            self.ui.lockButton.setText("Unlock")
            self.ui.statusbar.showMessage("Focused", 2000)
            indicationColor = Qt.darkGreen
        elif status == QCamera.Unlocked:
            self.ui.lockButton.setText("Focus")

            if reason == QCamera.LockFailed:
                self.ui.statusbar.showMessage("Focus Failed", 2000)
                indicationColor = Qt.red

        palette = self.ui.lockButton.palette()
        palette.setColor(QPalette.ButtonText, indicationColor)
        self.ui.lockButton.setPalette(palette)

    def takeImage(self):
        self.isCapturingImage = True
        self.imageCapture.capture()

    def startCamera(self):
        self.camera.start()

    def stopCamera(self):
        self.camera.stop()

    def updateCaptureMode(self):
        tabIndex = self.ui.captureWidget.currentIndex()
        captureMode = QCamera.CaptureStillImage if tabIndex == 0 else QCamera.CaptureVideo

        if self.camera.isCaptureModeSupported(captureMode):
            self.camera.setCaptureMode(captureMode)

    def updateCameraState(self, state):
        if state == QCamera.ActiveState:
            self.ui.actionStartCamera.setEnabled(False)
            self.ui.actionStopCamera.setEnabled(True)
            self.ui.captureWidget.setEnabled(True)
            self.ui.actionSettings.setEnabled(True)
        elif state in (QCamera.UnloadedState, QCamera.LoadedState):
            self.ui.actionStartCamera.setEnabled(True)
            self.ui.actionStopCamera.setEnabled(False)
            self.ui.captureWidget.setEnabled(False)
            self.ui.actionSettings.setEnabled(False)

    def updateRecorderState(self, state):
        if state == QMediaRecorder.StoppedState:
            self.ui.recordButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(True)
            self.ui.stopButton.setEnabled(False)
        elif state == QMediaRecorder.PausedState:
            self.ui.recordButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(False)
            self.ui.stopButton.setEnabled(True)
        elif state == QMediaRecorder.RecordingState:
            self.ui.recordButton.setEnabled(False)
            self.ui.pauseButton.setEnabled(True)
            self.ui.stopButton.setEnabled(True)

    def setExposureCompensation(self, index):
        self.camera.exposure().setExposureCompensation(index * 0.5)

    def displayRecorderError(self):
        QMessageBox.warning(self, "Capture error",
                self.mediaRecorder.errorString())

    def displayCameraError(self):
        QMessageBox.warning(self, "Camera error", self.camera.errorString())

    def updateCameraDevice(self, action):
        self.setCamera(action.data())

    def displayViewfinder(self):
        self.ui.stackedWidget.setCurrentIndex(0)

    def displayCapturedImage(self):
        self.ui.stackedWidget.setCurrentIndex(1)

    def readyForCapture(self, ready):
        self.ui.takeImageButton.setEnabled(ready)

    def imageSaved(self, id, fileName):
        self.isCapturingImage = False

        if self.applicationExiting:
            self.close()

    def closeEvent(self, event):
        if self.isCapturingImage:
            self.setEnabled(False)
            self.applicationExiting = True
            event.ignore()
        else:
            event.accept()
示例#28
0
class AvatarWidget(QWizardPage):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setSubTitle(self.tr("<h2>Create Your Avatar</h2>"))

        vlayout = QVBoxLayout(self)

        labelLayout = QHBoxLayout()
        labelImage = QLabel()
        labelImage.setPixmap(QPixmap(":/data/images/preferences-desktop-personal.png"))
        labelImage.setMaximumSize(64, 64)
        labelLayout.addWidget(labelImage)

        label = QLabel(self)
        label.setWordWrap(True)
        label.setText(self.tr("<p>This screen helps you set your <strong>user picture</strong>. You can either choose an image from a \
        file or you can capture an image from your camera. Select an option from the <strong>options</strong> menu.</p>"))
        labelLayout.addWidget(label)
        vlayout.addLayout(labelLayout)

        vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred))

        centerLayout = QHBoxLayout()
        centerLayout.addItem(QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))

        groupBox = QGroupBox()
        groupBox.setMaximumWidth(500)
        vlayout2 = QVBoxLayout(groupBox)
        hlayout = QHBoxLayout()

        comboBox = QComboBox()
        comboBox.setMinimumWidth(250)
        comboBox.addItems([self.tr("Options"), self.tr("Choose an image...")])

        #Camera control
        self.cameraInfo = None
        self.camera = None
        self.cameraImageCapture = None
        cameras = QCameraInfo.availableCameras()

        if len(cameras):
            self.cameraInfo = cameras[0]
            comboBox.addItem(self.tr("Camera ") + self.cameraInfo.deviceName())
            self.camera = QCamera(self.cameraInfo)
            self.camera.setCaptureMode(QCamera.CaptureStillImage)
            self.cameraImageCapture = QCameraImageCapture(self.camera)
            self.imageProcessing = self.camera.imageProcessing()
            self.imageProcessing.setWhiteBalanceMode(QCameraImageProcessing.WhiteBalanceSunlight)
            self.imageProcessing.setContrast(1)
            self.imageProcessing.setSaturation(1)
            self.imageProcessing.setSharpeningLevel(1)
            self.imageProcessing.setDenoisingLevel(1)
            #self.imageProcessing.setColorFilter(QCameraImageProcessing.ColorFilterWhiteboard) #FIXME Qt5.5
            self.cameraImageCapture.imageCaptured.connect(self.imageCapture)

        self.buttonCam = QPushButton()
        self.buttonCam.setText(self.tr("Capture"))
        self.buttonCam.setIcon(QIcon(":/data/images/webcamreceive.png"))
        self.buttonCam.setVisible(False)

        self.buttonReplay = QPushButton()
        self.buttonReplay.setText(self.tr("Recapture"))
        self.buttonReplay.setIcon(QIcon(":/data/images/view-refresh.png"))
        self.buttonReplay.setVisible(False)

        hlayout.addWidget(comboBox)
        hlayout.addItem(QSpacerItem(300, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))
        hlayout.addWidget(self.buttonCam)
        hlayout.addWidget(self.buttonReplay)

        vlayout2.addLayout(hlayout)

        hlayout2 = QHBoxLayout()

        hlayout2.addItem(QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))

        self.cameraLabel = QLabel()
        self.cameraLabel.setScaledContents(True)
        self.cameraLabel.setStyleSheet("background-color: black;")
        self.cameraLabel.setMinimumSize(320, 240)
        self.cameraLabel.setMaximumSize(320, 240)

        self.cameraView = QCameraViewfinder()
        self.cameraView.setMaximumSize(320,240)
        self.cameraView.setMinimumSize(320,240)
        self.cameraView.hide()

        hlayout2.addWidget(self.cameraLabel)
        hlayout2.addWidget(self.cameraView)

        hlayout2.addItem(QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))
        vlayout2.addLayout(hlayout2)

        centerLayout.addWidget(groupBox)
        centerLayout.addItem(QSpacerItem(40, 20, QSizePolicy.Preferred, QSizePolicy.Preferred))
        vlayout.addLayout(centerLayout)
        vlayout.addItem(QSpacerItem(20, 40, QSizePolicy.Preferred, QSizePolicy.Preferred))

        comboBox.currentIndexChanged.connect(self.avatarSelect)
        self.buttonCam.clicked.connect(self.buttonCamChanged)
        self.buttonReplay.clicked.connect(self.buttonReplayChanged)

        self.userAvatar = None

    def avatarSelect(self, index):
        if index == 0:
            if self.camera != None:
                self.camera.stop()
            self.buttonReplay.hide()
            self.buttonCam.hide()
            self.cameraView.hide()
            self.cameraLabel.show()
        elif index == 1:
            if self.camera != None:
                self.camera.stop()
            self.userAvatar = None
            self.buttonReplay.hide()
            self.buttonCam.hide()
            self.cameraView.hide()
            self.cameraLabel.show()
            file_url, file_type = QFileDialog.getOpenFileName(self, self.tr("Choose Avatar"), QDir.homePath(), "Image (*.png *.jpg)")
            if file_url != "":
                p = QPixmap(file_url)
                self.cameraLabel.setPixmap(p)
                self.userAvatar = file_url
        elif index == 2:
            self.userAvatar = None
            self.cameraLabel.hide()
            self.cameraView.show()
            self.camera.setViewfinder(self.cameraView)
            self.camera.start()
            self.buttonCam.setVisible(True)
            self.buttonReplay.hide()

    def buttonCamChanged(self):
        self.buttonCam.hide()
        self.buttonReplay.show()
        self.camera.searchAndLock()
        self.cameraImageCapture.capture("/tmp/avatar.png")
        self.camera.unlock()
        self.userAvatar = "/tmp/avatar.png"

    def buttonReplayChanged(self):
        self.userAvatar = None
        self.buttonReplay.hide()
        self.buttonCam.show()
        self.camera.start()
        self.cameraLabel.hide()
        self.cameraView.show()

    def imageCapture(self, id, preview):
        pixmap = QPixmap.fromImage(preview)
        self.camera.stop()
        self.cameraView.hide()
        self.cameraLabel.show()
        self.cameraLabel.setPixmap(pixmap)

    def execute(self):
        if self.userAvatar:
            if os.path.exists(os.path.join(os.environ["HOME"], ".face.icon")):
                os.remove(os.path.join(os.environ["HOME"], ".face.icon"))
            shutil.copy(self.userAvatar, os.path.join(os.environ["HOME"], ".face.icon"))
示例#29
0
class Camera(QObject):
    def __init__(self, parent=QObject()):
        super(Camera, self).__init__(parent)
        # chooses the system default camera
        self.cam = QCamera()
        self.imageCapture = QCameraImageCapture(self.cam)
        self.caminfo = QCameraInfo(self.cam)
        self.camvfind = QCameraViewfinder()
        self.camvfindset = QCameraViewfinderSettings()
        self.recorder = QMediaRecorder(self.cam)

    def init_camera(self):
        cameras = QCameraInfo.availableCameras()
        for cameraInfo in cameras:
            # select the capturing device if it is available
            if cameraInfo.description().find("Capture") is not -1:
                self.cam = QCamera(cameraInfo)
                self.caminfo = QCameraInfo(self.cam)
                self.recorder = QMediaRecorder(self.cam)
            print("Camera Chosen: " + self.caminfo.description())
        print(self.cam.supportedViewfinderFrameRateRanges())
        self.cam.setCaptureMode(QCamera.CaptureStillImage)
        if self.cam.isCaptureModeSupported(QCamera.CaptureStillImage):
            print("Capturemode supported")
        self.cam.load()
        self.cam.setViewfinder(self.camvfind)
        self.cam.start()

        self.imageCapture = QCameraImageCapture(self.cam)
        self.imageCapture.setCaptureDestination(
            QCameraImageCapture.CaptureToBuffer)

    def capture_still(self):
        self.imageCapture.capture()

    def setOnCapture(self, callback=None):
        self.imageCapture.imageCaptured.connect(callback)

    def start_vid(self):
        self.cam.load()
        # self.camvfind.show()
        self.cam.setViewfinder(self.camvfind)
        self.cam.setCaptureMode(QCamera.CaptureVideo)
        self.cam.start()

        audio = QAudioEncoderSettings()
        audio.setCodec("audio/amr")
        audio.setQuality(QtMultimedia.QMultimedia.NormalQuality)
        video = QVideoEncoderSettings()
        # video.setCodec("video/mp4")
        video.setQuality(QtMultimedia.QMultimedia.NormalQuality)
        video.setResolution(1920, 1080)
        video.setFrameRate(30.0)
        # self.recorder.setAudioSettings(audio)
        self.recorder.setVideoSettings(video)
        self.recorder.setContainerFormat("mp4")

        print("Output Loc: " + str(self.recorder.outputLocation()))

    def start_recording(self):
        directory = os.path.abspath(str(os.getcwd()))
        filename = "test" + str(time.time()) + ".mp4"
        abs_path = os.path.join(directory, filename)
        self.recorder.setOutputLocation(QUrl(abs_path))
        self.recorder.record()

    def stop_recording(self):
        self.recorder.stop()
示例#30
0
class Camera(QWidget):
    def __init__(self, parent=None, standalone=False):
        super(Camera, self).__init__(parent)

        # This prevents doing unneeded initialization
        # when QtDesginer loads the plugin.
        if parent is None and not standalone:
            return

        if not multimedia_available:
            return

        self.ui = uic.loadUi(os.path.join(WIDGET_PATH, "camera.ui"), self)

        self.camera = None
        self.imageCapture = None
        self.mediaRecorder = None
        self.isCapturingImage = False
        self.applicationExiting = False

        self.imageSettings = QImageEncoderSettings()
        self.audioSettings = QAudioEncoderSettings()
        self.videoSettings = QVideoEncoderSettings()
        self.videoContainerFormat = ''

        camera_device = QByteArray()

        videoDevicesGroup = QActionGroup(self)

        videoDevicesGroup.setExclusive(True)

        if not QCamera.availableDevices():
            self.ui.devicesCombo.addItem("No Device")
        else:
            for deviceName in QCamera.availableDevices():
                description = QCamera.deviceDescription(deviceName)
                self.ui.devicesCombo.addItem(description)

                videoDeviceAction = QAction(description, videoDevicesGroup)
                videoDeviceAction.setCheckable(True)
                videoDeviceAction.setData(deviceName)

                if camera_device.isEmpty():
                    cameraDevice = deviceName
                    videoDeviceAction.setChecked(True)

                self.ui.devicesCombo.addAction(videoDeviceAction)

        videoDevicesGroup.triggered.connect(self.updateCameraDevice)

        self.ui.captureWidget.currentChanged.connect(self.updateCaptureMode)

        self.ui.devicesCombo.currentIndexChanged.connect(
            self.get_device_action)

        self.ui.lockButton.hide()

        # Start camera 2s after the UI has loaded
        QTimer.singleShot(2000, lambda: self.setCamera(camera_device))

    def setCamera(self, cameraDevice):
        try:
            if cameraDevice.isEmpty():
                self.camera = QCamera()
            else:
                self.camera = QCamera(cameraDevice)

            self.camera.stateChanged.connect(self.updateCameraState)
            self.camera.error.connect(self.displayCameraError)

            self.mediaRecorder = QMediaRecorder(self.camera)
            self.mediaRecorder.stateChanged.connect(self.updateRecorderState)

            self.imageCapture = QCameraImageCapture(self.camera)

            self.mediaRecorder.durationChanged.connect(self.updateRecordTime)
            self.mediaRecorder.error.connect(self.displayRecorderError)

            self.mediaRecorder.setMetaData(QMediaMetaData.Title,
                                           "Camera Widget")

            self.ui.exposureCompensation.valueChanged.connect(
                self.setExposureCompensation)

            self.camera.setViewfinder(self.ui.viewfinder)

            self.updateCameraState(self.camera.state())
            self.updateLockStatus(self.camera.lockStatus(),
                                  QCamera.UserRequest)
            self.updateRecorderState(self.mediaRecorder.state())

            self.imageCapture.readyForCaptureChanged.connect(
                self.readyForCapture)
            self.imageCapture.imageCaptured.connect(self.processCapturedImage)
            self.imageCapture.imageSaved.connect(self.imageSaved)

            self.camera.lockStatusChanged.connect(self.updateLockStatus)

            self.ui.captureWidget.setTabEnabled(
                0,
                self.camera.isCaptureModeSupported(QCamera.CaptureStillImage))
            self.ui.captureWidget.setTabEnabled(
                1, self.camera.isCaptureModeSupported(QCamera.CaptureVideo))

            self.updateCaptureMode()
            self.camera.start()
        except:
            pass

    def keyPressEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_CameraFocus:
            self.displayViewfinder()
            self.camera.searchAndLock()
            event.accept()
        elif event.key() == Qt.Key_Camera:
            if self.camera.captureMode() == QCamera.CaptureStillImage:
                self.takeImage()
            elif self.mediaRecorder.state() == QMediaRecorder.RecordingState:
                self.stop()
            else:
                self.record()

            event.accept()
        else:
            super(Camera, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.isAutoRepeat():
            return

        if event.key() == Qt.Key_CameraFocus:
            self.camera.unlock()
        else:
            super(Camera, self).keyReleaseEvent(event)

    def updateRecordTime(self):
        msg = "Recorded {} sec".format(self.mediaRecorder.duration())
        self.ui.timeLabel.text = msg
        print(msg)

    def processCapturedImage(self, requestId, img):
        scaledImage = img.scaled(self.ui.viewfinder.size(), Qt.KeepAspectRatio,
                                 Qt.SmoothTransformation)

        self.ui.lastImagePreviewLabel.setPixmap(QPixmap.fromImage(scaledImage))

        self.displayCapturedImage()
        QTimer.singleShot(4000, self.displayViewfinder)

    def configureSettings(self):

        settings_dialog = Settings(self.mediaRecorder, self.imageCapture)

        settings_dialog.setImageSettings(self.imageSettings)
        settings_dialog.setAudioSettings(self.audioSettings)
        settings_dialog.setVideoSettings(self.videoSettings)

        settings_dialog.setFormat(self.videoContainerFormat)
        # settings_dialog.setStreamingSettings(self.streamingSettings)

        if settings_dialog.exec_():
            self.imageSettings = settings_dialog.imageSettings()
            self.audioSettings = settings_dialog.audioSettings()
            self.videoSettings = settings_dialog.videoSettings()
            self.videoContainerFormat = settings_dialog.format()

            self.imageCapture.setEncodingSettings(self.imageSettings)
            self.mediaRecorder.setEncodingSettings(self.audioSettings,
                                                   self.videoSettings,
                                                   self.videoContainerFormat)

    def record(self):
        self.mediaRecorder.record()
        self.updateRecordTime()

    def pause(self):
        self.mediaRecorder.pause()

    def stop(self):
        self.mediaRecorder.stop()

    def setMuted(self, muted):
        self.mediaRecorder.setMuted(muted)

    def toggleLock(self):
        if self.camera.lockStatus() in (QCamera.Searching, QCamera.Locked):
            self.camera.unlock()
        elif self.camera.lockStatus() == QCamera.Unlocked:
            self.camera.searchAndLock()

    def updateLockStatus(self, status, reason):
        indicationColor = Qt.black

        if status == QCamera.Searching:
            self.ui.statusbar.showMessage("Focusing...")
            self.ui.lockButton.setText("Focusing...")
            indicationColor = Qt.yellow
        elif status == QCamera.Locked:
            self.ui.lockButton.setText("Unlock")
            self.ui.statusbar.showMessage("Focused", 2000)
            indicationColor = Qt.darkGreen
        elif status == QCamera.Unlocked:
            self.ui.lockButton.setText("Focus")

            if reason == QCamera.LockFailed:
                self.ui.statusbar.showMessage("Focus Failed", 2000)
                indicationColor = Qt.red

        palette = self.ui.lockButton.palette()
        palette.setColor(QPalette.ButtonText, indicationColor)
        self.ui.lockButton.setPalette(palette)

    def takeImage(self):
        self.isCapturingImage = True
        self.imageCapture.capture()

    def startCamera(self):
        self.camera.start()

    def stopCamera(self):
        self.camera.stop()

    def updateCaptureMode(self):
        tabIndex = self.ui.captureWidget.currentIndex()
        captureMode = QCamera.CaptureStillImage if tabIndex == 0 else QCamera.CaptureVideo

        if self.camera.isCaptureModeSupported(captureMode):
            self.camera.setCaptureMode(captureMode)

    def updateCameraState(self, state):
        if state == QCamera.ActiveState:
            self.ui.actionStartCamera.setEnabled(False)
            self.ui.actionStopCamera.setEnabled(True)
            self.ui.captureWidget.setEnabled(True)
            self.ui.actionSettings.setEnabled(True)
        elif state in (QCamera.UnloadedState, QCamera.LoadedState):
            self.ui.actionStartCamera.setEnabled(True)
            self.ui.actionStopCamera.setEnabled(False)
            self.ui.captureWidget.setEnabled(False)
            self.ui.actionSettings.setEnabled(False)

    def updateRecorderState(self, state):
        if state == QMediaRecorder.StoppedState:
            self.ui.recordButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(True)
            self.ui.stopButton.setEnabled(False)
        elif state == QMediaRecorder.PausedState:
            self.ui.recordButton.setEnabled(True)
            self.ui.pauseButton.setEnabled(False)
            self.ui.stopButton.setEnabled(True)
        elif state == QMediaRecorder.RecordingState:
            self.ui.recordButton.setEnabled(False)
            self.ui.pauseButton.setEnabled(True)
            self.ui.stopButton.setEnabled(True)

    def setExposureCompensation(self, index):
        self.camera.exposure().setExposureCompensation(index * 0.5)

    def displayRecorderError(self):
        QMessageBox.warning(self, "Capture error",
                            self.mediaRecorder.errorString())

    def displayCameraError(self):
        QMessageBox.warning(self, "Camera error", self.camera.errorString())

    def get_device_action(self, index):
        self.ui.devicesCombo.actions()[index].trigger()

    def updateCameraDevice(self, action):
        self.setCamera(action.data())

    def displayViewfinder(self):
        self.ui.stackedWidget.setCurrentIndex(0)

    def displayCapturedImage(self):
        self.ui.stackedWidget.setCurrentIndex(1)

    def readyForCapture(self, ready):
        self.ui.takeImageButton.setEnabled(ready)

    def imageSaved(self, id, fileName):
        self.isCapturingImage = False

        if self.applicationExiting:
            self.close()

    def closeEvent(self, event):
        if self.isCapturingImage:
            self.setEnabled(False)
            self.applicationExiting = True
            event.ignore()
        else:
            event.accept()