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

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

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

    def saveImage(self, requestId, image):
        print('test3')
        image: PyQt5.QtMultimedia.QVideoFrame
        image = qimage2numpy2(image.image())
        print(image.shape)
        cv2.imwrite('/Users/xiaozhenlong/Desktop/tmp/test3.jpg', image)
class CameraWidget(QWidget):
    def __init__(self, background_color):
        QWidget.__init__(self)

        self.scene = QGraphicsScene(self)
        self.scene.setBackgroundBrush(QBrush(background_color))
        self.graphics_view = QGraphicsView(self.scene)
        self.graphics_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.graphics_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.graphics_view.setFrameStyle(0)
        self.graphics_view.setStyleSheet(
            "QGraphicsView {background: transparent; border: 3px; outline: none;}"
        )
        self.graphics_view.scale(-1,
                                 1)  # this make live video from camero mirror.
        self.video_item = QGraphicsVideoItem()
        self.scene.addItem(self.video_item)

        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.addWidget(self.graphics_view)

        self.available_cameras = QCameraInfo.availableCameras()

        # Set the default camera.
        self.select_camera(0)

    def resizeEvent(self, event):
        self.video_item.setSize(
            QSizeF(event.size().width(),
                   event.size().height()))
        QWidget.resizeEvent(self, event)

    def select_camera(self, i):
        self.camera = QCamera(self.available_cameras[i])
        self.camera.setViewfinder(self.video_item)
        self.camera.setCaptureMode(QCamera.CaptureStillImage)
        self.camera.start()

    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 stop_camera(self):
        self.camera.stop()
Пример #3
0
class ImgCapture(QCameraImageCapture):
	"""
	
	"""

	#当拍照完成, 并且已经保存完图片发送本信号
	cameraCapOk = pyqtSignal(str)

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

		self.camera = QCamera()
		self.camera.setCaptureMode(QCamera.CaptureStillImage);

		self.setMediaObject(self.camera)
		# self.setCaptureDestination(QCameraImageCapture.CaptureToFile)

		self.imageSaved.connect(self._captureComplete)
		self.imageCaptured.connect(self._imageCaptured)


	#图片保存的目录
	def cameraCapture(self,filename):
		self.camera.start()
		self.capture(filename)


	#屏幕截图,保存图片到指定目录下
	def screenCapture(self,filename):
		"""

		同 cameraCapture

		"""
		im = ImageGrab.grab()

		im.save(filename,'jpeg')


	def _imageCaptured(self,id,qImg):
		pass

	def _captureComplete(self,id,filename):
		self.camera.stop()
		self.cameraCapOk.emit(filename)
Пример #4
0
class mainApp(QMainWindow):
    def __init__(self):
        super(mainApp, self).__init__()
        self.resize(600, 400)
        self.mainUI()
        self.setCentralWidget(self.widget)

    def mainUI(self):
        self.pushButton = QPushButton("Camera")
        layout = QVBoxLayout()
        layout.addWidget(self.pushButton)
        self.widget = QWidget()
        self.widget.setLayout(layout)
        self.pushButton.clicked.connect(self.showCamera)

    def showCamera(self):
        self.finder = QCameraViewfinder()
        self.finder.show()

        self.camera = QCamera()
        self.camera.setViewfinder(self.finder)
        self.camera.start()
        self.camera.stop()
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")
Пример #6
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)
Пример #7
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()
Пример #8
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)))
Пример #9
0
class CQCameraPreviewWindow(QtWidgets.QMainWindow):
    closeSignal = QtCore.pyqtSignal()
    ioctlRequest = QtCore.pyqtSignal(dict)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def is_save_state_needed(self):
        return False

    def save_state(self):
        pass

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

    def closeEvent(self, event):
        if self.is_save_state_needed():
            self.save_state()
        self.stop_preview()
        self.closeSignal.emit()
Пример #10
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"))
Пример #11
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
Пример #12
0
class FaceRecognitionAppUI(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent=parent)
        self.ui = Ui_FaceRecApp()

        self.ui.setupUi(self)
        self.camera = None
        self.running = False
        # self.face_recognizer = AwsFaceRecognizer()
        self.face_recognizer = EdgeFaceRecognizer()
        self.populate_face_registry_list()

        if CAMERA_TYPE == 'OpenCV':
            self.setup_opencv_camera()
        else:
            self.setup_camera()

        self.timer = QTimer(self, interval=5)
        self.timer.timeout.connect(self.process)

    def populate_face_registry_list(self):
        self.ui.faceRegistrySelect.blockSignals(True)
        for item in range(self.ui.faceRegistrySelect.count()):
            self.ui.faceRegistrySelect.removeItem(item)
        for registry in self.face_recognizer.list_face_registries():
            self.ui.faceRegistrySelect.addItem(registry)
        self.ui.faceRegistrySelect.blockSignals(False)

        if self.ui.faceRegistrySelect.currentText():
            self.set_current_registry(self.ui.faceRegistrySelect.currentText())

    def start(self):
        self.start_camera()
        self.timer.start()
        self.running = True

    def pause(self):
        pass

    def stop(self):
        self.timer.stop()
        logger.info('Stopping the app')
        self.running = False
        self.stop_camera()

    def register_faces(self):
        self.stop_camera()
        registration_dialog = FaceRegistrationView(
            parent=self, face_recognizer=self.face_recognizer)
        registration_dialog.exec_()
        logger.info('Done registering faces')
        self.start_camera()

    def create_registry(self):
        dialog = CreateRegistryView(parent=self,
                                    face_recognizer=self.face_recognizer)
        dialog.exec_()
        self.populate_face_registry_list()

    def delete_registry(self):
        dialog = DeleteRegistryView(parent=self,
                                    face_recognizer=self.face_recognizer)
        dialog.exec_()
        self.populate_face_registry_list()

    def set_current_registry(self, registry):
        assert registry is not None and registry != ''
        self.face_recognizer.set_active_face_registry(registry)

    def view_registry(self):
        self.stop_camera()
        registry_dialog = FaceRegistryView(
            parent=self, face_recognizer=self.face_recognizer)
        registry_dialog.exec_()
        self.start_camera()

    def setup_camera(self):
        camera_device = QByteArray()

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

        for device in QCamera.availableDevices():
            description = QCamera.deviceDescription(device)
            video_device_action = QAction(description, video_devices_group)
            video_device_action.setCheckable(True)
            video_device_action.setData(device)

            if camera_device.isEmpty():
                camera_device = device
                video_device_action.setChecked(True)

            self.ui.menuDevices.addAction(video_device_action)
        if camera_device.isEmpty():
            self.camera = QCamera()
        else:
            self.camera = QCamera(camera_device)
        self.camera.setViewfinder(self.ui.cameraViewFinder)

    def setup_opencv_camera(self):
        if len(QCamera.availableDevices()) > 0:
            camera_addr = str(QCamera.availableDevices()[0])
            self.camera = cv2.VideoCapture(0)
            if self.camera.isOpened():
                self.camera.set(cv2.CAP_PROP_BUFFERSIZE, 1)
                self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
                self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
                logger.info('Opened the camera {}'.format(camera_addr))
            else:
                logger.error(
                    'Failed to open the camera {}'.format(camera_addr))

    def stop_camera(self):
        if self.camera is None:
            return
        if CAMERA_TYPE == 'OpenCV':
            self.camera.release()
        else:
            self.camera.stop()

    def start_camera(self):
        if self.camera is None:
            return
        if CAMERA_TYPE == 'OpenCV':
            self.camera.open(0)
        else:
            self.camera.start()

    def update_frame(self):
        read, frame = self.camera.read()
        self.display_frame(frame)

    def display_frame(self, frame):
        if frame is None:
            return
        qformat = QImage.Format_Indexed8
        if len(frame.shape) == 3:
            if frame.shape[2] == 4:
                qformat = QImage.Format_RGBA8888
            else:
                qformat = QImage.Format_RGB888
        qt_image = QImage(frame, frame.shape[1], frame.shape[0],
                          frame.strides[0], qformat)
        qt_image = qt_image.rgbSwapped()
        self.ui.cameraSurface.setPixmap(QPixmap.fromImage(qt_image))
        self.update()

    def process(self):
        assert self.camera is not None
        read, frame = self.camera.read()
        if not read:
            return
        recognition_results = self.face_recognizer.recognize_faces(frame)
        AwsFaceRecognizer.draw_face_recognitions(frame, recognition_results)
        self.display_frame(frame)

    def run_recognizer_with_opencv(self):
        self.camera.stop()
        cur_registry = self.ui.faceRegistrySelect.currentText()
        self.face_recognizer.set_active_face_registry(cur_registry)
        cap = cv2.VideoCapture(0)
        cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
        if not cap.isOpened():
            logger.warning('Unable to open the webcam')
            return

        cv2.namedWindow('Face recognizer', cv2.WINDOW_NORMAL)
        count = 0
        while True:
            read, frame = cap.read()
            if not read:
                logger.warning('Unable to read video frame')
                break
            recognition_results = self.face_recognizer.recognize_faces(frame)
            count += 1
            print('{}'.format(count), end='\r')
            sys.stdout.flush()

            AwsFaceRecognizer.draw_face_recognitions(frame,
                                                     recognition_results)
            cv2.imshow('Face recognizer', frame)
            key = cv2.waitKey(5) & 255
            if key == 27:
                break
        cv2.destroyAllWindows()
class UiMainWindow(QWidget):
    """Main UI window of the application.

	Attributes:
	----------
	window_width: int
		Width of the window
	window_height: int
		Height of the window
	button_width: int
		Width of buttons
	button_height: int
		Height of buttons
	dist: int
		Distance to the edge of Widgets(Window/Button/Label...)
	model_selected: bool
		Shows whether a model is selected or not
	"""
    window_height = 650
    window_width = 800
    button_width = 180
    button_height = 50
    dist = 30
    model_selected = False
    textbox_height = 25
    small_button_width = 100
    small_button_height = 30
    debug_height = 200
    debug_mode = False
    accepted_download = False
    current_city = ""

    def __init__(self, parent) -> None:
        super().__init__(parent)

        main_window.setObjectName("main_window")
        main_window.resize(self.window_width, self.window_height)
        self.centralwidget = QWidget(main_window)
        self.centralwidget.setObjectName("centralwidget")
        self.detector = Detection()

        self.Box_Stadt = QComboBox(self.centralwidget)
        self.Box_Stadt.setGeometry(
            QRect(self.dist, self.dist, self.button_width, self.button_height))
        self.Box_Stadt.setObjectName("Box_Stadt")
        self.Box_Stadt.activated.connect(self.on_dropdown_selected)
        # dynamic city updates
        supported_cities_updater = Thread(target=update_dropdown,
                                          daemon=True,
                                          args=(self.Box_Stadt, ))
        supported_cities_updater.start()

        self.Text_City = QLineEdit(self.centralwidget)
        self.Text_City.setGeometry(
            QRect(self.dist + self.dist + self.button_width, self.dist + 10,
                  self.button_width, self.textbox_height))
        self.Text_City.setObjectName("Text_City")
        self.Text_City.setToolTip(
            'Enter a city you wish to detect sights in that you cannot find in the dropdown on the left after updating.'
        )

        self.Button_City = QPushButton(self.centralwidget)
        self.Button_City.setGeometry(
            QRect(
                int(2.3 * self.dist) + self.button_width + self.button_width,
                self.dist + 8, self.small_button_width,
                self.small_button_height))
        self.Button_City.setObjectName("Button_City")
        self.Button_City.clicked.connect(self.request_city)

        self.Button_Detection = QPushButton(self.centralwidget)
        self.Button_Detection.setGeometry(
            QRect(
                self.window_width - (self.dist + self.button_width),
                self.window_height - (self.dist + self.button_height + 20),
                self.button_width,
                self.button_height,
            ))
        self.Button_Detection.setObjectName("Button_Detection")
        self.Button_Detection.clicked.connect(self.detect_sights)

        self.Button_Bild = QPushButton(self.centralwidget)
        self.Button_Bild.setGeometry(
            QRect(
                self.dist,
                self.window_height - (self.dist + self.button_height + 20),
                self.button_width,
                self.button_height,
            ))
        self.Button_Bild.setObjectName("Button_Bild")
        self.Button_Bild.clicked.connect(lambda: self.camera_viewfinder.hide())
        self.Button_Bild.clicked.connect(
            lambda: self.Box_Camera_selector.setCurrentIndex(0))
        self.Button_Bild.clicked.connect(
            lambda: self.stacked_widget.setCurrentIndex(0))
        self.Button_Bild.clicked.connect(lambda: self.Label_Bild.show())
        self.Button_Bild.clicked.connect(self.dragdrop)

        self.available_cameras = QCameraInfo.availableCameras()

        self.Box_Camera_selector = QComboBox(self.centralwidget)
        self.Box_Camera_selector.setGeometry(
            QRect(
                self.window_width - (self.dist + self.button_width),
                self.dist,
                self.button_width,
                self.button_height,
            ))
        self.Box_Camera_selector.setObjectName("Box_Camera_selector")
        self.Box_Camera_selector.addItem("")
        # self.Box_Camera_selector.addItems([camera.description() for camera in self.available_cameras])
        self.Box_Camera_selector.addItems([
            "Camera " + str(i) + ": " +
            str(self.available_cameras[i].description())
            for i in range(len(self.available_cameras))
        ])
        self.Box_Camera_selector.currentIndexChanged.connect(
            self.select_camera)

        self.stacked_widget = QStackedWidget(self.centralwidget)
        label_height = (self.window_height - self.dist - self.button_height -
                        self.dist) - (self.dist + self.button_height +
                                      self.dist)
        label_start_y = self.dist + self.button_height + self.dist
        self.stacked_widget.setGeometry(
            QRect(
                self.dist,
                label_start_y,
                self.window_width - (self.dist * 2),
                label_height,
            ))

        self.camera_viewfinder = QCameraViewfinder()

        self.Label_Bild = ImageLabel(self)
        self.Label_Bild.setGeometry(
            QRect(0, 0, self.window_width - (self.dist * 2), label_height))

        self.checkBoxImprove = QCheckBox(
            "Help improving SightScan's detection quality", self.centralwidget)
        self.checkBoxImprove.setObjectName(u"improvement")
        self.checkBoxImprove.setGeometry(QRect(self.dist, 5, 350, 20))
        self.checkBoxImprove.setChecked(False)
        self.checkBoxImprove.stateChanged.connect(self.set_improve_quality_var)

        self.checkBox = QCheckBox("Debug", self.centralwidget)
        self.checkBox.setObjectName(u"checkBox")
        self.checkBox.setGeometry(
            QRect(self.window_width - (self.dist + 50),
                  self.window_height - (self.dist + 20), 70, 20))
        self.checkBox.setChecked(False)
        self.checkBox.stateChanged.connect(self.debug_click)

        # Setup logging
        fn = "logs/" + datetime.now().strftime(
            '%d_%m_%Y__%H_%M_%S') + 'log.log'
        if not os.path.exists("logs"):
            os.mkdir("logs")
        f = '%(asctime)s :: %(levelname)s :: %(filename)s :: %(funcName)s :: %(lineno)d :: %(message)s'
        self.textDebug = QTextEditLogger(self.centralwidget)
        self.textDebug.setFormatter(logging.Formatter(f))
        logging.basicConfig(filename=fn, format=f, level=logging.DEBUG)
        logging.getLogger().addHandler(self.textDebug)

        # Log Text Box in GUI
        self.textDebug.widget.setObjectName(u"textEdit")
        self.textDebug.widget.setEnabled(False)
        self.textDebug.widget.setGeometry(
            QRect(self.dist, self.window_height,
                  self.window_width - 2 * self.dist,
                  self.debug_height - self.dist))
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(
            self.textDebug.widget.sizePolicy().hasHeightForWidth())
        self.textDebug.widget.setSizePolicy(size_policy)
        self.textDebug.widget.setReadOnly(True)

        self.stacked_widget.addWidget(self.Label_Bild)
        self.stacked_widget.addWidget(self.camera_viewfinder)

        main_window.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(main_window)
        self.menubar.setGeometry(QRect(0, 0, 678, 21))
        self.menubar.setObjectName("menubar")
        main_window.setMenuBar(self.menubar)

        self.statusbar = QStatusBar(main_window)
        self.statusbar.setObjectName("statusbar")
        main_window.setStatusBar(self.statusbar)

        main_window.setWindowIcon(QIcon(logo_without_text))

        self.retranslateUi(main_window)
        QMetaObject.connectSlotsByName(main_window)

    def set_improve_quality_var(self):
        self.improve_checkbox_enabled = self.checkBoxImprove.isChecked()

    def retranslateUi(self, main_window: QMainWindow) -> None:
        """Set the text initially for all items.

		Parameters
		----------
		main_window: QMainWindow
		    The instance of the prepared application window
		"""
        _translate = QCoreApplication.translate
        main_window.setWindowTitle(_translate(WINDOW, "SightScan"))
        self.Box_Stadt.addItems(['Choose City'] + initialize_cities())
        self.Box_Camera_selector.setItemText(
            0, _translate(WINDOW, "Choose Webcam"))
        self.Button_Detection.setText(_translate(WINDOW, START))
        self.Button_Bild.setText(_translate(WINDOW, ENABLE))
        self.Button_City.setText(_translate(WINDOW, "Add City"))

    def on_dropdown_selected(self) -> None:
        """Shows a pop-up for confirming the download of the selected city."""
        city_pretty_print = self.Box_Stadt.currentText()
        city = self.Box_Stadt.currentText().replace(' ', '_').upper()

        if city != "CHOOSE_CITY":
            self.current_city = self.Box_Stadt.currentText()
            # if no connection to dos
            if get_supported_cities() == []:
                latest_version = "couldn't get the latest version"
                downloaded_version = "couldn't get the downloaded version"
                print('no connection to dos')

            # if connection to dos
            else:
                downloaded_version = -1  # initialization

                Path("weights").mkdir(mode=0o700, exist_ok=True)

                if not os.path.exists("weights/versions.txt"):
                    with open('weights/versions.txt',
                              'w'):  # creating a version file
                        pass

                with open("weights/versions.txt", "r") as file:
                    for line in file:
                        elements = line.split("=")
                        if elements[0].upper() == city:
                            downloaded_version = int(elements[1])
                            break

                latest_version = get_dwh_model_version(city)

                if downloaded_version == -1:
                    msg = QMessageBox()
                    msg.setWindowTitle("Download City")
                    msg.setWindowIcon(QIcon(logo_without_text))
                    msg.setText("Do you want to download " +
                                city_pretty_print + "?")
                    msg.setIcon(QMessageBox.Question)
                    msg.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
                    msg.setDefaultButton(QMessageBox.Ok)
                    msg.setInformativeText("When downloaded, sights of " +
                                           city_pretty_print +
                                           " can be detected.")
                    msg.buttonClicked.connect(self.handover_city)

                    msg.exec_()

                elif latest_version > downloaded_version:
                    update_msg = QMessageBox()
                    update_msg.setWindowTitle("Update available")
                    update_msg.setWindowIcon(QIcon(logo_without_text))
                    update_msg.setText(
                        "Do you want to download an update for " + city + "?")
                    update_msg.setIcon(QMessageBox.Question)
                    update_msg.setStandardButtons(QMessageBox.Cancel
                                                  | QMessageBox.Ok)
                    update_msg.setDefaultButton(QMessageBox.Ok)
                    update_msg.setInformativeText(
                        "Updated cities can detect sights faster and more accurately. If you choose not to download, the "
                        + "detection will still work.")
                    update_msg.buttonClicked.connect(self.handover_city)

                    update_msg.exec_()
            if self.accepted_download is True or latest_version == downloaded_version:
                self.accepted_download = False
                self.show_download_result()
            self.model_selected = True
        else:
            self.model_selected = False

    def handover_city(self, button) -> None:
        """Starts the download of the pre-trained model of the selected city.

		Parameters
		----------
		button:
			Pushed button inside the popup.
		"""

        if "OK" in button.text().upper():
            city = self.Box_Stadt.currentText().replace(' ', '_').upper()
            self.model_selected = True
            model = get_downloaded_model(city)
            if model is not None:
                with open("weights/" + city + ".pt", "wb+") as file:
                    file.write(model)
            self.accepted_download = True
        elif "CANCEL" in button.text().upper():
            self.Box_Stadt.setCurrentIndex(0)

    def detect_sights(self) -> None:
        """Starts detection for the dropped image or shown webcam video
		with the downloaded model and displays the results in the label."""
        city = self.Box_Stadt.currentText().replace(' ', '_').upper()
        print("Detection Status: " + str(self.detector.detection))

        if self.model_selected is False:
            self.show_missing_model_popup()
        else:
            # start drag&drop image detection
            if self.stacked_widget.currentIndex() == 0 and self.Button_Bild.text() == DISABLE and \
              self.Label_Bild.image != logo_with_text:
                print(f"Starting detection of {self.Label_Bild.image}")
                wipe_prediction_input_images(INPUT_PREDICTION_DIR)
                shutil.copy2(self.Label_Bild.image, INPUT_PREDICTION_DIR)
                self.detector.enable_detection()
                self.detector.detect(self,
                                     weights='weights/' + city + '.pt',
                                     debug=self.debug_mode)
            # stop video detection
            elif self.stacked_widget.currentIndex(
            ) == 0 and self.Button_Detection.text() == STOP:
                self.stop_video_detection()
                time.sleep(2)
                self.reactivate_cam()
            # if webcam activated
            elif self.stacked_widget.currentIndex() == 1:
                if self.Button_Detection.text() == START:
                    self.Button_Detection.setText(
                        QCoreApplication.translate(WINDOW, STOP))
                    self.Label_Bild.setStyleSheet("""
					""")
                    print("Video Detection Started")
                    self.prep_video_detection()
                    source = self.Box_Camera_selector.currentIndex()
                    self.detector.enable_detection()
                    self.detection_thread = Thread(target=self.detector.detect,
                                                   args=(self, ),
                                                   kwargs={
                                                       'weights':
                                                       'weights/' + city +
                                                       '.pt',
                                                       'source':
                                                       str(source - 1),
                                                       'image_size':
                                                       704,
                                                       'debug':
                                                       self.debug_mode
                                                   })
                    self.detection_thread.start()
            else:
                print("Drop a File or select a Webcam!")

    def show_missing_model_popup(self) -> None:
        # Show Pop Up to choose a city
        emsg = QMessageBox()
        emsg.setWindowTitle("No city chosen")
        emsg.setWindowIcon(QIcon(logo_without_text))
        emsg.setText(
            "You need to choose a city before the detection can start.")
        emsg.setIcon(QMessageBox.Warning)
        emsg.setStandardButtons(QMessageBox.Ok)
        emsg.setDefaultButton(QMessageBox.Ok)

        emsg.exec_()

    def show_download_result(self) -> None:
        # city_pretty_print = self.Box_Stadt.currentText()

        self.model_selected = True
        newest_vers_msg = QMessageBox()
        newest_vers_msg.setWindowTitle("Ready for Detection!")
        newest_vers_msg.setWindowIcon(QIcon(logo_without_text))
        newest_vers_msg.setText("You can start detecting sights in " +
                                self.current_city + "!")
        newest_vers_msg.setStandardButtons(QMessageBox.Ok)
        newest_vers_msg.setDefaultButton(QMessageBox.Ok)

        newest_vers_msg.exec_()

    def request_city(self) -> None:
        # Send entered city to dwh and show confirmation popup if the city name is known
        city_input = self.Text_City.text()
        city_request = city_input.upper()
        if len(filter_city(city_input)) == 1:
            send_city_request(city_request)

            cmsg = QMessageBox()
            cmsg.setWindowTitle("Request confirmed")
            cmsg.setWindowIcon(QIcon(logo_without_text))
            cmsg.setText("Your request to add support for " + city_input +
                         " has been sent to our backend.")
            cmsg.setStandardButtons(QMessageBox.Ok)
            cmsg.setDefaultButton(QMessageBox.Ok)
            cmsg.exec_()
        else:
            cmsg = QMessageBox()
            cmsg.setWindowTitle("Unknown city name")
            cmsg.setWindowIcon(QIcon(logo_without_text))
            cmsg.setText(
                "The typed city name is not known. Please check the spelling.")
            cmsg.setIcon(QMessageBox.Warning)
            cmsg.setStandardButtons(QMessageBox.Ok)
            cmsg.setDefaultButton(QMessageBox.Ok)
            cmsg.exec_()

    def dragdrop(self) -> None:
        """Enables / disables Drag&Drop of images."""
        if self.Button_Bild.text() == ENABLE:
            # stop video detection if active
            if self.Button_Detection.text() == STOP:
                self.Button_Detection.setText(
                    QCoreApplication.translate(WINDOW, START))
                self.detector.disable_detection()
            self.Label_Bild.setAcceptDrops(True)
            self.Label_Bild.setText("\n\n Drop Image here \n\n")
            self.Label_Bild.setStyleSheet("""
				QLabel{
					border: 4px dashed #aaa
				}
			""")
            self.Button_Bild.setText(
                QCoreApplication.translate(WINDOW, DISABLE))
        elif self.Button_Bild.text() == DISABLE:
            self.Label_Bild.setAcceptDrops(False)
            self.Label_Bild.setText("")
            self.Label_Bild.setStyleSheet("")
            self.Label_Bild.image = logo_with_text
            self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
            self.Button_Bild.setText(QCoreApplication.translate(
                WINDOW, ENABLE))

    def select_camera(self, i):
        """Starts the selected camera. If "Choose webcam" is selected, it stops the camera.

		Parameters
		----------
		i:
			Index of the chosen camera.
		"""
        self.Label_Bild.image = logo_with_text
        self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
        if i == 0:
            self.camera.stop()
            self.detector.disable_detection()
            self.Button_Detection.setText(
                QCoreApplication.translate(WINDOW, START))
            self.stacked_widget.setCurrentIndex(0)
            self.camera_viewfinder.hide()
            self.Label_Bild.show()
            time.sleep(2)
            self.Label_Bild.image = logo_with_text
            self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
            self.Label_Bild.setStyleSheet("""
			""")
        else:
            self.camera_viewfinder.show()
            self.stacked_widget.setCurrentIndex(1)
            self.Label_Bild.hide()
            self.camera = QCamera(self.available_cameras[i - 1])
            self.camera.setViewfinder(self.camera_viewfinder)
            self.camera.error.connect(
                lambda: self.alert(self.camera.errorString()))
            self.camera.start()
            self.Button_Bild.setText(QCoreApplication.translate(
                WINDOW, ENABLE))

    def prep_video_detection(self) -> None:
        self.camera.stop()
        self.camera_viewfinder.hide()
        self.stacked_widget.setCurrentIndex(0)
        self.Label_Bild.image = loading_image
        self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
        self.Label_Bild.show()

    def stop_video_detection(self) -> None:
        self.Button_Detection.setText(QCoreApplication.translate(
            WINDOW, START))
        self.detector.disable_detection()
        self.stacked_widget.setCurrentIndex(1)
        self.Label_Bild.hide()
        self.camera_viewfinder.show()

    def debug_click(self, state):
        self.debug_mode = bool(state)

        if state:
            main_window.resize(self.window_width,
                               self.window_height + self.debug_height)
            self.textDebug.widget.setEnabled(True)
        else:
            main_window.resize(self.window_width, self.window_height)
            self.textDebug.widget.setEnabled(False)

    def reactivate_cam(self) -> None:
        self.Label_Bild.image = logo_with_text
        self.Label_Bild.setPixmap(QPixmap(self.Label_Bild.image))
        self.camera.start()

    def close_all(self) -> None:
        if self.Button_Detection.text() == STOP:
            self.detector.disable_detection()
            self.stop_video_detection()
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()
Пример #15
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()
Пример #16
0
class QtCamera(Camera):

    class VideoSurface(QAbstractVideoSurface):

        class ConversionThread(QThread):
            ndarray_available = pyqtSignal(np.ndarray)

            def __init__(self):
                super().__init__()
                self._mutex = QMutex()
                self._abort = False
                self._condition = QWaitCondition()
                self.frame = None

            def process_frame(self, frame: QVideoFrame):
                with QMutexLocker(self._mutex):
                    self.frame = frame

                if not self.isRunning():
                    self.start()
                else:
                    self._condition.wakeOne()

            def stop(self):
                with QMutexLocker(self._mutex):
                    self._abort = True
                    self._condition.wakeOne()

            def run(self):
                self._abort = False

                while True:
                    with QMutexLocker(self._mutex):
                        if self._abort:
                            break
                        frame = self.frame
                        self.frame = None

                    pixel_format = frame.pixelFormat()
                    image_format = QVideoFrame.imageFormatFromPixelFormat(pixel_format)
                    if image_format == QImage.Format_Invalid:
                        qDebug("WARNING: Could not convert video frame to image!")
                        return
                    if not frame.map(QAbstractVideoBuffer.ReadOnly):
                        qDebug("WARNING: Could not map video frame!")
                        return

                    width = frame.width()
                    height = frame.height()
                    bytes_per_line = frame.bytesPerLine()
                    image = QImage(frame.bits(), width, height, bytes_per_line, image_format)
                    image = image.convertToFormat(QImage.Format_RGB32)

                    frame.unmap()

                    # fix upside-down data for windows
                    if platform.system() == "Windows":
                        image = image.mirrored(vertical=True)

                    # now convert QImage to ndarray
                    pointer = image.constBits()
                    pointer.setsize(image.byteCount())
                    array = np.array(pointer).reshape(image.height(), image.width(), 4)

                    # get rid of the transparency channel and organize the colors as rgb
                    # NB: it would be safer to figure out the image format first, and where the transparency channel is
                    # stored...
                    array = array[:, :, 0:3:][:, :, ::-1]

                    self.ndarray_available.emit(array)

                    # see if new data is available, go to sleep if not
                    with QMutexLocker(self._mutex):
                        if self.frame is None:
                            self._condition.wait(self._mutex)

        ndarray_available = pyqtSignal(np.ndarray)

        supportedFormats = [
            QVideoFrame.Format_RGB32,
            QVideoFrame.Format_ARGB32
        ]

        def __init__(self, parent=None):
            super().__init__()
            self._source = None
            self.conversion_thread = self.ConversionThread()
            self.conversion_thread.ndarray_available.connect(self.ndarray_available)

        # method for QAbstractVideoSurface
        def supportedPixelFormats(self, handleType=QAbstractVideoBuffer.NoHandle):
            return self.supportedFormats

        # method for QAbstractVideoSurface
        def isFormatSupported(self, fmt: QVideoSurfaceFormat):
            return fmt in self.supportedFormats

        # method for QAbstractVideoSurface
        def present(self, frame: QVideoFrame):
            if frame.isValid():
                self.conversion_thread.process_frame(frame)
                return True
            return False

    def __init__(self, parent=None, device=None):
        super().__init__(self)
        self._manualMode = False
        self._active = False

        self._video_surface = self.VideoSurface()
        self._video_surface.ndarray_available.connect(self.ndarray_available)

        self._camera = QCamera(device)
        self._camera.setViewfinder(self._video_surface)
        error = self._camera.error()
        if error != QCamera.NoError:
            qDebug("Camera error: ", error)

        self.maxval = 2**8

    def __del__(self):
        self._camera.stop()
        self._video_surface.stop()
        self._video_surface.conversion_thread.stop()
        self._video_surface.conversion_thread.wait()

    def _valid(self):
        return True

    @pyqtSlot()
    def start(self):
        self._camera.start()

    @pyqtSlot()
    def stop(self):
        self._camera.stop()

    def get_exposure(self):
        return NotImplementedError()

    def get_exposure_range(self):
        return NotImplementedError()

    def is_auto_exposure(self):
        return NotImplementedError()

    def set_auto_exposure(self, auto):
        return NotImplementedError()

    def is_auto_gain(self):
        return NotImplementedError()

    def set_auto_gain(self, auto):
        return NotImplementedError()

    def get_gain(self):
        return NotImplementedError()

    def get_gain_range(self):
        return NotImplementedError()

    def set_exposure(self, exposure):
        return NotImplementedError()

    def set_gain(self, gain):
        return NotImplementedError()
Пример #17
0
class CMainWindow(QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(CMainWindow, self).__init__(*args, **kwargs)
        self.oc_camera = None
        self.l_cameras = QCameraInfo.availableCameras()
        if len(self.l_cameras) == 0:
            self.fatal_error("No cameras found!")

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

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

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

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

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

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

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

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

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

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

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

    def closeEvent(self, event):
        self.stop_preview()
Пример #18
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
Пример #19
0
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()
Пример #20
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"))
Пример #21
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)
Пример #22
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()
Пример #23
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()
Пример #24
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()