def start_ui(self): self.zui = Ui_zwin() self.zui.setupUi(self) self.zui.camera_label.setScaledContents(True) # 初始化信息 self.zui.label_xuehao.setText("工号:") self.zui.label_mingzi.setText("姓名:") self.zui.label_time.setText("签到时间:") # 查询按钮 self.zui.cxbtn.clicked.connect(self.cx_ui) # 注册按钮 self.zui.zcbtn.clicked.connect(self.zq_zc) # 签到按钮 self.zui.qdbtn.clicked.connect(self.zq_qd) # 删除按钮 self.zui.del_btn.clicked.connect(self.del_yg) # 导出按钮 self.zui.out_btn.clicked.connect(self.out_ex) # 摄像头控制 camera = QCamera(self) # 创建摄像头 cameraviewfinder = QCameraViewfinder(self.zui.camera_label) # 创建显示窗口 cameraviewfinder.resize(752, 420) self.cameraImageCapture = QCameraImageCapture(camera) # 绑定获取的摄像头 self.cameraImageCapture.setCaptureDestination( QCameraImageCapture.CaptureToFile) # 获取数据类型 camera.setCaptureMode(QCamera.CaptureStillImage) camera.setViewfinder(cameraviewfinder) # 绑定窗口 camera.start() # 开启摄像头
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()
class Camera(QObject): def __init__(self, parent = QObject()): super(Camera, self).__init__(parent) print("3") self.cam = QCamera(QCameraInfo.defaultCamera()) #"/dev/video0".encode() print("4") self.caminfo = QCameraInfo(self.cam) self.camvfind = QCameraViewfinder() self.camvfindset = QCameraViewfinderSettings() self.cammode = self.cam.CaptureMode(0) self.camimgcap = QCameraImageCapture(self.cam) def iniCamera(self): print(self.caminfo.description()) print(self.caminfo.availableCameras()) for caminfo in QCameraInfo.availableCameras(): print(caminfo.deviceName()) if self.cam.isCaptureModeSupported(self.cammode): print("Capturemode supported") def startVid(self): #self.camimgcap.CaptureDestination(2) self.camvfind.show() self.cam.setViewfinder(self.camvfind) self.cam.setCaptureMode(self.cammode) self.cam.start()
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) try: 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) except: save_path = str(Path(os.path.expanduser("~/Downloads"))) 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("Save photo at: " + photo_path)
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 Camera(QObject): def __init__(self, parent=QObject()): super(Camera, self).__init__(parent) # chooses the system default camera self.cam = QCamera() self.caminfo = QCameraInfo(self.cam) self.camvfind = QCameraViewfinder() self.camvfindset = QCameraViewfinderSettings() self.recorder = QMediaRecorder(self.cam) def iniCamera(self): cameras = QCameraInfo.availableCameras() for cameraInfo in cameras: # select the capturing device if it is available if (cameraInfo.description().find("Capture") is not -1): self.cam = QCamera(cameraInfo) self.caminfo = QCameraInfo(self.cam) self.recorder = QMediaRecorder(self.cam) print("Camera Chosen: " + self.caminfo.description()) print(self.cam.supportedViewfinderFrameRateRanges()) if self.cam.isCaptureModeSupported(QCamera.CaptureVideo): print("Capturemode supported") def startVid(self): self.cam.load() # self.camvfind.show() self.cam.setViewfinder(self.camvfind) self.cam.setCaptureMode(QCamera.CaptureVideo) self.cam.start() audio = QAudioEncoderSettings() audio.setCodec("audio/amr") audio.setQuality(QtMultimedia.QMultimedia.NormalQuality) video = QVideoEncoderSettings() # video.setCodec("video/mp4") video.setQuality(QtMultimedia.QMultimedia.NormalQuality) video.setResolution(1920, 1080) video.setFrameRate(30.0) # self.recorder.setAudioSettings(audio) self.recorder.setVideoSettings(video) self.recorder.setContainerFormat("mp4") def startRecording(self, filename): directory = os.path.abspath(str(os.getcwd())) abs_path = os.path.join(directory, filename) self.recorder.setOutputLocation(QUrl(abs_path)) self.recorder.record() def stopRecording(self): self.recorder.stop() def getViewFinder(self): return self.camvfind
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(QFrame.NoFrame) 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.setSpacing(0) 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())))) return image_capture.capture(photo_path) def stop_camera(self): self.camera.stop()
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)
class MainWindow(QMainWindow, camtest_auto.Ui_MainWindow): # access variables inside of the UI's file def setImagae(self, image): if not image: return pMap = QPixmap.fromImage(image) self.labelCamera1.setPixmap(pMap) def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) # gets defined in the UI file # th = CamThread(self) # th.changePixmap.connect(self.setImagae) # th.start() self.cam = QCamera() self.cam.setViewfinder(self.widget) self.cam.start()
class Camera(QtWidgets.QWidget): def __init__(self): super().__init__() self.setupUi() cameraDevice = '' 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 not cameraDevice: cameraDevice = deviceName videoDeviceAction.setChecked(True) self.setCamera(cameraDevice) self.show() def setupUi(self): self.gridLayout_3 = QtWidgets.QGridLayout(self) self.viewfinder = QCameraViewfinder() self.gridLayout_3.addWidget(self.viewfinder, 0, 0, 1, 1) def setCamera(self, cameraDevice): if cameraDevice.isEmpty(): self.camera = QCamera() else: self.camera = QCamera(cameraDevice) self.camera.setViewfinder(self.viewfinder) self.camera.start() def updateCameraDevice(self, action): self.setCamera(action.data())
def _start_video(self): from PyQt5.QtMultimedia import QCameraInfo, QCamera, QVideoFrame cam_list = QCameraInfo.availableCameras() if len(cam_list) == 0: from chimerax.core.errors import UserError raise UserError('Did not find any cameras') if len(cam_list) > 1: self.session.logger.info('Found multiple cameras: %s' % ', '.join(c.description() for c in cam_list)) cam_info = cam_list[0] self.camera_name = cam_info.description() # self.session.logger.info('Using camera "%s"' % cam_info.description()) cam = QCamera(cam_info) self._camera = cam # print('camera availability (0 = available):', cam.availability()) cam.setCaptureMode(QCamera.CaptureVideo) cam.stateChanged.connect(self._camera_state_changed) cam.start()
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()
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")
class VideoWindow(QMainWindow): def __init__(self, parent=None): super(VideoWindow, self).__init__(parent) self.setWindowTitle( "PyQt Video Player Widget Example - pythonprogramminglanguage.com") self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.camera = QCamera(0) self.cameraviewfinder = QCameraViewfinder() self.cameramode = self.camera.CaptureMode(2) self.cameraimgcap = QCameraImageCapture(self.camera) videoWidget = QVideoWidget() self.imageView = QLabel("add a image file") self.imageView.setAlignment(Qt.AlignCenter) self.playButton = QPushButton() self.playButton.setEnabled(True) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.scene1 = QGraphicsScene() self.view1 = QGraphicsView(self.scene1) # Create new action # Create exit action # Create a widget for window contents wid = QWidget(self) self.setCentralWidget(wid) # Create layouts to place inside widget # controlLayout = QHBoxLayout() # controlLayout.setContentsMargins(0, 0, 0, 0) # controlLayout.addWidget(self.playButton) # controlLayout.addWidget(self.positionSlider) videolayout = QVBoxLayout() videolayout.addWidget(videoWidget) # videolayout.addLayout(controlLayout) # Set widget to contain window contents layout = QHBoxLayout() layout.addLayout(videolayout) layout.addWidget(self.cameraviewfinder) # layout.addWidget(self.view1) wid.setLayout(layout) self.mediaPlayer.setVideoOutput(videoWidget) self.cameraviewfinder.show() self.camera.setViewfinder(self.cameraviewfinder) def exitCall(self): sys.exit(app.exec_()) def play(self): self.showFullScreen() fileName = 'D:\\桌面\\some.mp4' if fileName != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(fileName))) self.playButton.setEnabled(True) self.cameraviewfinder.resize(640, 480) self.camera.start() self.mediaPlayer.play() camera_capture = cv2.VideoCapture(0) while True: ret, camera_frame = camera_capture.read() if ret: self.displayImage(camera_frame) else: break camera_capture.release() cv2.destroyAllWindows() def mediaStateChanged(self, state): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playButton.setIcon(self.style().standardIcon( QStyle.SP_MediaPause)) else: self.playButton.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) def displayImage(self, img): self.scene1.clear() pixMap = QPixmap(img) w, h = pixMap.width(), pixMap.height() self.scene1.addPixmap(pixMap) self.view1.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio) self.scene1.update()
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()
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()
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()
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ from PyQt5.QtMultimedia import QCamera, QCameraImageCapture from PyQt5 import QtMultimediaWidgets cm = QCamera() viewfinder = QtMultimediaWidgets.QCameraViewfinder() viewfinder.show() cm.setViewfinder(viewfinder) cp = QCameraImageCapture(cm) cm.setCaptureMode(cm.CaptureStillImage) cm.start() cm.searchAndLock() cp.capture() cm.unlock()
class mainInterface(QWidget): # 定义信号 processFinished = pyqtSignal(dict) def __init__(self): """ 初始化 :return: null """ # 超类初始化 super().__init__() # UI初始化 self.ui = Ui_mainWidget() self.ui.setupUi(self) self.grabKeyboard() self.setMouseTracking(True) self.setWindowFlags(Qt.FramelessWindowHint) self.setWindowIcon(QIcon('OCR.ico')) # 初始化相机 self.camera = QCamera() self.imageCapture = QCameraImageCapture(self.camera) self.viewsetting = QCameraViewfinderSettings() self.initimplement() # 初始化标题栏 self.initTitleBar() # 初始化系统托盘 self.tray = QSystemTrayIcon() self.tray.setIcon(QIcon('OCR.ico')) self.initTray() # OCR识别部分 self.OCR = ocr() self.OCR.setappid('1257206643') self.OCR.setsecretid('AKIDFTddWEg9Ncsz0sE7oOpBNOExdDdeCUJ3') self.OCR.setsecretkey('FQitsgUND8yfrZK0RrBMOJB5tWhCm5Ol') # 初始化登录部分 self.logWidget = QWidget() self.logui = Ui_Form() self.logui.setupUi(self.logWidget) self.logWidget.setWindowFlags(Qt.FramelessWindowHint) self.logWidget.setWindowModality(Qt.ApplicationModal) self.logui.close_btn.clicked.connect(self.logWidget.close) # 初始化变量 self.mousePressd = False self.mousePoint = None self.result = {} self.isFirst = False self.ocrType = ocrType.ocr_general # 默认为印刷体识别 # 初始化字定义信号连接 self.processFinished.connect(self.updateOCRInfo) self.ui.btn_login.clicked.connect(self.logWidget.show) self.ui.comboBox_choose.currentIndexChanged.connect(self.changeocrType) def initTitleBar(self): """ 初始化标题栏 :return: null """ self.ui.frame.setStyleSheet( "QFrame#frame{background-color:rgb(244, 76, 76);}") self.ui.label_logo.setStyleSheet( "QLabel{border-image:url(./image/ocr.png);}") self.ui.label_title.setStyleSheet( "QLabel{border-image:url(./image/iOCR.png);}") self.ui.comboBox_choose.setStyleSheet( "QComboBox {border-radius:15px;border: 2px solid #4AFFF4;font-family:'楷体';font-size:20px;}" "QComboBox QAbstractItemView::item{height:50px;width:200px;}" "QComboBox::down-arrow{image: url(./image/arrow.png);width:25px;height:25px;}" "QComboBox::drop-down {subcontrol-origin: padding;subcontrol-position:top right;border:none;margin-right:30px;}" "QComboBox::down-arrow:hover{image:url(./image/arrow_hover.png);width:25px;height:25px;}" "QComboBox::down-arrow:on {top: 1px;left: 1px;}") self.ui.comboBox_choose.insertItem(0, ' 印刷体识别') self.ui.comboBox_choose.insertItem(1, ' 手写体识别') self.ui.comboBox_choose.insertItem(2, ' 身份证识别') self.ui.comboBox_choose.insertItem(3, ' 名片识别') self.ui.comboBox_choose.insertItem(4, ' 银行卡识别') self.ui.btn_login.setStyleSheet( "QPushButton{border-image:url(./image/default-portrait.png);}") self.ui.btn_setting.setStyleSheet( "QPushButton{border-image:url(./image/settings.png);}" "QPushButton:hover{border-image:url(./image/qcconfig-hover.png);}") self.ui.btn_min.setStyleSheet( "QPushButton{border-image:url(./image/mini_new.png);}" "QPushButton:hover{border-image:url(./image/mini_hover_new.png);}") self.ui.btn_close.setStyleSheet( "QPushButton{border-image:url(./image/close.png);}" "QPushButton:hover{border-image:url(./image/close-hover.png);}") self.ui.checkBox_cam.setStyleSheet( "QCheckBox{spacing: 5px;font-size: 24px;vertical-align:middle}" "QCheckBox::indicator { width: 45px;height: 45px;}" "QCheckBox::indicator::unchecked {image: url(./image/close_cam.png);}" "QCheckBox::indicator::checked { image: url(./image/open_cam.png);}" ) self.ui.captureBtn.setStyleSheet( "QPushButton{border-style: outset;border-width: 2px;border-color: rgb(82,215,100);border-radius: 5px;font-size: 24px;}" "QPushButton:pressed{background-color: rgb(176,215,181);border-style: inset;}" ) self.ui.checkBox_cam.setChecked(True) self.ui.btn_close.clicked.connect(lambda: qApp.quit()) self.ui.btn_min.clicked.connect(self.miniToTray) self.ui.checkBox_cam.stateChanged.connect(self.camControl) def initTray(self): """ 初始化系统托盘信息 :return: """ tray_menu = QMenu() restoreAction = QAction('&Show', self) quitAction = QAction('&Quit', self) tray_menu.addAction(restoreAction) tray_menu.addAction(quitAction) self.tray.setContextMenu(tray_menu) restoreAction.triggered.connect(self.trayActivatedEvent) quitAction.triggered.connect(qApp.quit) self.tray.activated.connect(self.trayActivatedEvent) def initimplement(self): """ 初始化实现端口 :return: ui """ camInfo = QCameraInfo(self.camera) if camInfo.defaultCamera().isNull(): QMessageBox.warning(self, 'Warning', 'No available camera!', QMessageBox.Ok) return -1 else: self.ui.caputurePhoto.setText(camInfo.description()) self.camera.setViewfinder(self.ui.cameraShow) self.camera.setCaptureMode(QCamera.CaptureStillImage) self.camera.load() resolution = self.camera.supportedViewfinderResolutions() if len(resolution) != 0: if QSize(640, 480) in resolution: self.viewsetting.setResolution(QSize(640, 480)) elif QSize(640, 360) in resolution: self.viewsetting.setResolution(QSize(640, 360)) else: self.viewsetting.setResolution(resolution[0]) self.camera.setViewfinderSettings(self.viewsetting) # ------------------------------Note-------------------------------- # 此种方法利用摄像头准备捕捉图像的状态来进行捕捉图像,readyForCapture # 为true时,才进行捕捉图像,详见下面捕捉函数槽函数。这种方法将进行不 # 停的捕捉,将每次捕捉的相邻图像进行图像相似度判断。当图像相似度低于 # 阈值时,认定为新图像,才进行OCR识别。否则仅捕捉图像而不进行识别。当 # 然捕捉图像速度过于太快时,可以用定时器,每隔0.5秒,去检查readyFor # Capture状态位,进而有效控制程序资源。 # 本应用中采用按键捕捉方式,非自动,详见下面按键捕捉事件 # ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ # self.imageCapture.readyForCaptureChanged.connect(self.captureimage) self.camera.start() self.ui.caputurePhoto.setScaledContents(True) self.imageCapture.setCaptureDestination( QCameraImageCapture.CaptureToBuffer) self.imageCapture.imageCaptured.connect(self.displayimage) self.ui.captureBtn.clicked.connect(self.openDlg) def displayimage(self, num, image): """ 显示图形 :param num: number :param image: image :return: null """ self.ui.caputurePhoto.setPixmap(QPixmap.fromImage(image)) self.ui.ocrInfo.setText('识别中......') t = threading.Thread(target=self.ocrForImage, args=(image, )) t.start() # def captureimage(self, state): # """ # 捕捉图像槽函数 # :state: 状态变量 # :return: null # """ # if state is True: # self.camera.searchAndLock() # self.imageCapture.capture() # self.camera.unlock() # def saveimage(self): # """ # 保存图像槽函数 # :return: null # """ # pix = QPixmap(self.ui.caputurePhoto.pixmap()) # if pix: # pix.save(r'D://1.png', 'PNG') # QMessageBox.information(self, 'Message', 'Capture Successfully', QMessageBox.Ok) def ocrForImage(self, image): """ 为截取的图片进行ocr识别 :param image: QImage :return: null """ # Note:子线程里不能对ui界面做改动,ui界面修改只能在主线程中修改,下面注释的做法是错误的 # self.ui.ocrInfo.setText('识别中......') byte = QByteArray() buffer = QBuffer(byte) buffer.open(QIODevice.WriteOnly) image.save(buffer, 'PNG') if self.ocrType == ocrType.ocr_general: self.result = self.OCR.client.general_detect( CIBuffers([byte.data()])) elif self.ocrType == ocrType.ocr_handwriting: self.result = self.OCR.client.handwriting_detect( CIBuffers([byte.data()])) elif self.ocrType == ocrType.ocr_idcard: self.result = self.OCR.client.idcard_detect( CIBuffers([byte.data()]), 0) elif self.ocrType == ocrType.ocr_namecard: self.result = self.OCR.client.namecard_detect( CIBuffers([byte.data()]), 0) elif self.ocrType == ocrType.ocr_bankcard: self.result = self.OCR.client.bankcard_detect( CIBuffers([byte.data()])) else: pass self.processFinished.emit(self.result) def updateOCRInfo(self, res): """ 将ocr识别结果显示在信息框中 :param res: :return: """ if self.ocrType == ocrType.ocr_general or self.ocrType == ocrType.ocr_handwriting: if res['code'] == 0 and res['message'] == 'OK': self.ui.ocrInfo.setText('OK') ocrInfo = [] for i in range(len(self.result['data']['items'])): ocrInfo.append( self.result['data']['items'][i]['itemstring']) self.ui.ocrInfo.setText(''.join(ocrInfo)) else: self.ui.ocrInfo.setText('识别失败!') elif self.ocrType == ocrType.ocr_bankcard: if res['code'] == 0 and res['message'] == 'OK': self.ui.ocrInfo.setText('OK') ocrInfo = [] for i in range(len(self.result['data']['items'])): ocrInfo.append(self.result['data']['items'][i]['item']) ocrInfo.append(':') ocrInfo.append( self.result['data']['items'][i]['itemstring']) ocrInfo.append('\n') self.ui.ocrInfo.setText(''.join(ocrInfo)) else: self.ui.ocrInfo.setText('识别失败!') elif self.ocrType == ocrType.ocr_idcard: if res['result_list'][0]['code'] == 0 and res['result_list'][0][ 'message'] == 'OK': self.ui.ocrInfo.setText('OK') ocrInfo = [] ocrInfo_keys = list( self.result['result_list'][0]['data'].keys()) ocrInfo_values = list( self.result['result_list'][0]['data'].values()) for i in range( len(self.result['result_list'][0]['data']) // 2): ocrInfo.append(ocrInfo_keys[i]) ocrInfo.append(':') ocrInfo.append(ocrInfo_values[i]) ocrInfo.append('\n') self.ui.ocrInfo.setText(''.join(ocrInfo)) else: self.ui.ocrInfo.setText('识别失败!') elif self.ocrType == ocrType.ocr_namecard: if res['result_list'][0]['code'] == 0 and res['result_list'][0][ 'message'] == 'OK': self.ui.ocrInfo.setText('OK') ocrInfo = [] for i in range(len(self.result['result_list'][0]['data'])): ocrInfo.append( self.result['result_list'][0]['data'][i]['item']) ocrInfo.append(':') ocrInfo.append( self.result['result_list'][0]['data'][i]['value']) ocrInfo.append('\n') self.ui.ocrInfo.setText(''.join(ocrInfo)) else: self.ui.ocrInfo.setText('识别失败!') else: pass def camControl(self, state): """ 槽函数 控制相机开关 :param state: checkbox开关状态 :return:null """ if state == Qt.Unchecked: self.ui.cameraShow.setUpdatesEnabled(False) elif state == Qt.Checked: self.ui.cameraShow.setUpdatesEnabled(True) else: return -1 def miniToTray(self): """ 槽函数 最小化到系统托盘 :return:null """ if not self.tray.isVisible(): self.tray.show() if self.tray.isVisible(): if self.isFirst is False: QMessageBox.information( self, "Systray", "The program will keep running in the " "system tray. To terminate the program, " "choose <b>Quit</b> in the context menu " "of the system tray entry.") self.isFirst = True self.hide() def trayActivatedEvent(self, reason): """ 槽函数 响应点击托盘图标 :param reason: 响应原因 :return: null """ if reason == QSystemTrayIcon.Context: pass else: self.tray.hide() self.show() def openDlg(self): """ 槽函数 打开对话框选取文件 :return:文件名 """ filename, filetype = QFileDialog.getOpenFileName( self, '选取图片', path.expanduser('~'), "Image Files (*.png *.jpg *.bmp)") if filename: if QFile(filename).size() >= 6291456: QMessageBox.information(self, '打开图片', '选择图片大于6MB大小,暂不支持识别,请重新选择。') self.openDlg() else: self.displayimage(0, QImage(filename)) def keyPressEvent(self, e): """ 槽函数 键盘按键响应事件 :param e: 按键事件 :return: null """ if e.key() == Qt.Key_Space: if self.imageCapture.isReadyForCapture(): self.camera.searchAndLock() self.imageCapture.capture() self.camera.unlock() def mouseMoveEvent(self, e): """ 槽函数 定义鼠标移动事件 :param e: QMouseEvent :return: null """ if (e.buttons() == Qt.LeftButton) and self.mousePressd: self.move(e.globalPos() - self.mousePoint) e.accept() def mousePressEvent(self, e): """ 槽函数 定义鼠标按下事件 :param e: QMouseEvent :return: null """ if e.button() == Qt.LeftButton: self.mousePressd = True self.mousePoint = e.globalPos() - self.pos() e.accept() def mouseReleaseEvent(self, e): """ 槽函数 定义鼠标松开事件 :param e: QMouseEvent :return: null """ self.mousePressd = False def changeocrType(self, index): """ 槽函数 改变ocr识别类型 :param index: int :return: null """ if index == 0: self.ocrType = ocrType.ocr_general elif index == 1: self.ocrType = ocrType.ocr_handwriting elif index == 2: self.ocrType = ocrType.ocr_idcard elif index == 3: self.ocrType = ocrType.ocr_namecard elif index == 4: self.ocrType = ocrType.ocr_bankcard else: pass
class QrReaderCameraDialog(Logger, MessageBoxMixin, QDialog): """ Dialog for reading QR codes from a camera """ # Try to crop so we have minimum 512 dimensions SCAN_SIZE: int = 512 qr_finished = pyqtSignal(bool, str, object) def __init__(self, parent, *, config: SimpleConfig): ''' Note: make sure parent is a "top_level_window()" as per MessageBoxMixin API else bad things can happen on macOS. ''' QDialog.__init__(self, parent=parent) Logger.__init__(self) self.validator: AbstractQrReaderValidator = None self.frame_id: int = 0 self.qr_crop: QRect = None self.qrreader_res: List[QrCodeResult] = [] self.validator_res: QrReaderValidatorResult = None self.last_stats_time: float = 0.0 self.frame_counter: int = 0 self.qr_frame_counter: int = 0 self.last_qr_scan_ts: float = 0.0 self.camera: QCamera = None self._error_message: str = None self._ok_done: bool = False self.camera_sc_conn = None self.resolution: QSize = None self.config = config # Try to get the QR reader for this system self.qrreader = get_qr_reader() if not self.qrreader: raise MissingQrDetectionLib( _("The platform QR detection library is not available.")) # Set up the window, add the maximize button flags = self.windowFlags() flags = flags | Qt.WindowMaximizeButtonHint self.setWindowFlags(flags) self.setWindowTitle(_("Scan QR Code")) self.setWindowModality( Qt.WindowModal if parent else Qt.ApplicationModal) # Create video widget and fixed aspect ratio layout to contain it self.video_widget = QrReaderVideoWidget() self.video_overlay = QrReaderVideoOverlay() self.video_layout = FixedAspectRatioLayout() self.video_layout.addWidget(self.video_widget) self.video_layout.addWidget(self.video_overlay) # Create root layout and add the video widget layout to it vbox = QVBoxLayout() self.setLayout(vbox) vbox.setContentsMargins(0, 0, 0, 0) vbox.addLayout(self.video_layout) self.lowres_label = QLabel( _("Note: This camera generates frames of relatively low resolution; QR scanning accuracy may be affected" )) self.lowres_label.setWordWrap(True) self.lowres_label.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter) vbox.addWidget(self.lowres_label) self.lowres_label.setHidden(True) # Create a layout for the controls controls_layout = QHBoxLayout() controls_layout.addStretch(2) controls_layout.setContentsMargins(10, 10, 10, 10) controls_layout.setSpacing(10) vbox.addLayout(controls_layout) # Flip horizontally checkbox with default coming from global config self.flip_x = QCheckBox() self.flip_x.setText(_("&Flip horizontally")) self.flip_x.setChecked(bool(self.config.get('qrreader_flip_x', True))) self.flip_x.stateChanged.connect(self._on_flip_x_changed) controls_layout.addWidget(self.flip_x) close_but = QPushButton(_("&Close")) close_but.clicked.connect(self.reject) controls_layout.addWidget(close_but) # Create the video surface and receive events when new frames arrive self.video_surface = QrReaderVideoSurface(self) self.video_surface.frame_available.connect(self._on_frame_available) # Create the crop blur effect self.crop_blur_effect = QrReaderCropBlurEffect(self) self.image_effect = ImageGraphicsEffect(self, self.crop_blur_effect) # Note these should stay as queued connections becasue we use the idiom # self.reject() and self.accept() in this class to kill the scan -- # and we do it from within callback functions. If you don't use # queued connections here, bad things can happen. self.finished.connect(self._boilerplate_cleanup, Qt.QueuedConnection) self.finished.connect(self._on_finished, Qt.QueuedConnection) def _on_flip_x_changed(self, _state: int): self.config.set_key('qrreader_flip_x', self.flip_x.isChecked()) def _get_resolution(self, resolutions: List[QSize], min_size: int) -> QSize: """ Given a list of resolutions that the camera supports this function picks the lowest resolution that is at least min_size in both width and height. If no resolution is found, NoCameraResolutionsFound is raised. """ def res_list_to_str(res_list: List[QSize]) -> str: return ', '.join( ['{}x{}'.format(r.width(), r.height()) for r in res_list]) def check_res(res: QSize): return res.width() >= min_size and res.height() >= min_size self.logger.info('searching for at least {0}x{0}'.format(min_size)) # Query and display all resolutions the camera supports format_str = 'camera resolutions: {}' self.logger.info(format_str.format(res_list_to_str(resolutions))) # Filter to those that are at least min_size in both width and height candidate_resolutions = [] ideal_resolutions = [r for r in resolutions if check_res(r)] less_than_ideal_resolutions = [ r for r in resolutions if r not in ideal_resolutions ] format_str = 'ideal resolutions: {}, less-than-ideal resolutions: {}' self.logger.info( format_str.format(res_list_to_str(ideal_resolutions), res_list_to_str(less_than_ideal_resolutions))) # Raise an error if we have no usable resolutions if not ideal_resolutions and not less_than_ideal_resolutions: raise NoCameraResolutionsFound( _("Cannot start QR scanner, no usable camera resolution found." ) + self._linux_pyqt5bug_msg()) if not ideal_resolutions: self.logger.warning( 'No ideal resolutions found, falling back to less-than-ideal resolutions -- QR recognition may fail!' ) candidate_resolutions = less_than_ideal_resolutions is_ideal = False else: candidate_resolutions = ideal_resolutions is_ideal = True # Sort the usable resolutions, least number of pixels first, get the first element resolution = sorted(candidate_resolutions, key=lambda r: r.width() * r.height(), reverse=not is_ideal)[0] format_str = 'chosen resolution is {}x{}' self.logger.info( format_str.format(resolution.width(), resolution.height())) return resolution, is_ideal @staticmethod def _get_crop(resolution: QSize, scan_size: int) -> QRect: """ Returns a QRect that is scan_size x scan_size in the middle of the resolution """ scan_pos_x = (resolution.width() - scan_size) // 2 scan_pos_y = (resolution.height() - scan_size) // 2 return QRect(scan_pos_x, scan_pos_y, scan_size, scan_size) @staticmethod def _linux_pyqt5bug_msg(): ''' Returns a string that may be appended to an exception error message only if on Linux and PyQt5 < 5.12.2, otherwise returns an empty string. ''' if (sys.platform == 'linux' and PYQT_VERSION < 0x050c02 # Check if PyQt5 < 5.12.2 on linux # Also: this warning is not relevant to APPIMAGE; so make sure # we are not running from APPIMAGE. and not os.environ.get('APPIMAGE')): # In this case it's possible we couldn't detect a camera because # of that missing libQt5MultimediaGstTools.so problem. return ("\n\n" + _( 'If you indeed do have a usable camera connected, then this error may be caused by bugs in previous PyQt5 versions on Linux. Try installing the latest PyQt5:' ) + "\n\n" + "python3 -m pip install --user -I pyqt5") return '' def start_scan(self, device: str = ''): """ Scans a QR code from the given camera device. If no QR code is found the returned string will be empty. If the camera is not found or can't be opened NoCamerasFound will be raised. """ self.validator = QrReaderValidatorCounted() self.validator.strong_count = 5 # FIXME: make this time based rather than framect based device_info = None for camera in QCameraInfo.availableCameras(): if camera.deviceName() == device: device_info = camera break if not device_info: self.logger.info( 'Failed to open selected camera, trying to use default camera') device_info = QCameraInfo.defaultCamera() if not device_info or device_info.isNull(): raise NoCamerasFound( _("Cannot start QR scanner, no usable camera found.") + self._linux_pyqt5bug_msg()) self._init_stats() self.qrreader_res = [] self.validator_res = None self._ok_done = False self._error_message = None if self.camera: self.logger.info( "Warning: start_scan already called for this instance.") self.camera = QCamera(device_info) self.camera.setViewfinder(self.video_surface) self.camera.setCaptureMode(QCamera.CaptureViewfinder) # this operates on camera from within the signal handler, so should be a queued connection self.camera_sc_conn = self.camera.statusChanged.connect( self._on_camera_status_changed, Qt.QueuedConnection) self.camera.error.connect( self._on_camera_error ) # log the errors we get, if any, for debugging # Camera needs to be loaded to query resolutions, this tries to open the camera self.camera.load() _camera_status_names = { QCamera.UnavailableStatus: _('unavailable'), QCamera.UnloadedStatus: _('unloaded'), QCamera.UnloadingStatus: _('unloading'), QCamera.LoadingStatus: _('loading'), QCamera.LoadedStatus: _('loaded'), QCamera.StandbyStatus: _('standby'), QCamera.StartingStatus: _('starting'), QCamera.StoppingStatus: _('stopping'), QCamera.ActiveStatus: _('active') } def _get_camera_status_name(self, status: QCamera.Status): return self._camera_status_names.get(status, _('unknown')) def _set_resolution(self, resolution: QSize): self.resolution = resolution self.qr_crop = self._get_crop(resolution, self.SCAN_SIZE) # Initialize the video widget #self.video_widget.setMinimumSize(resolution) # <-- on macOS this makes it fixed size for some reason. self.resize(720, 540) self.video_overlay.set_crop(self.qr_crop) self.video_overlay.set_resolution(resolution) self.video_layout.set_aspect_ratio(resolution.width() / resolution.height()) # Set up the crop blur effect self.crop_blur_effect.setCrop(self.qr_crop) def _on_camera_status_changed(self, status: QCamera.Status): if self._ok_done: # camera/scan is quitting, abort. return self.logger.info('camera status changed to {}'.format( self._get_camera_status_name(status))) if status == QCamera.LoadedStatus: # Determine the optimal resolution and compute the crop rect camera_resolutions = self.camera.supportedViewfinderResolutions() try: resolution, was_ideal = self._get_resolution( camera_resolutions, self.SCAN_SIZE) except RuntimeError as e: self._error_message = str(e) self.reject() return self._set_resolution(resolution) # Set the camera resolution viewfinder_settings = QCameraViewfinderSettings() viewfinder_settings.setResolution(resolution) self.camera.setViewfinderSettings(viewfinder_settings) # Counter for the QR scanner frame number self.frame_id = 0 self.camera.start() self.lowres_label.setVisible( not was_ideal ) # if they have a low res camera, show the warning label. elif status == QCamera.UnloadedStatus or status == QCamera.UnavailableStatus: self._error_message = _( "Cannot start QR scanner, camera is unavailable.") self.reject() elif status == QCamera.ActiveStatus: self.open() CameraErrorStrings = { QCamera.NoError: "No Error", QCamera.CameraError: "Camera Error", QCamera.InvalidRequestError: "Invalid Request Error", QCamera.ServiceMissingError: "Service Missing Error", QCamera.NotSupportedFeatureError: "Unsupported Feature Error" } def _on_camera_error(self, errorCode): errStr = self.CameraErrorStrings.get(errorCode, "Unknown Error") self.logger.info(f"QCamera error: {errStr}") def accept(self): self._ok_done = True # immediately blocks further processing super().accept() def reject(self): self._ok_done = True # immediately blocks further processing super().reject() def _boilerplate_cleanup(self): self._close_camera() if self.isVisible(): self.close() def _close_camera(self): if self.camera: self.camera.setViewfinder(None) if self.camera_sc_conn: self.camera.statusChanged.disconnect(self.camera_sc_conn) self.camera_sc_conn = None self.camera.unload() self.camera = None def _on_finished(self, code): res = ((code == QDialog.Accepted and self.validator_res and self.validator_res.accepted and self.validator_res.simple_result) or '') self.validator = None self.logger.info(f'closed {res}') self.qr_finished.emit(code == QDialog.Accepted, self._error_message, res) def _on_frame_available(self, frame: QImage): if self._ok_done: return self.frame_id += 1 if frame.size() != self.resolution: self.logger.info( 'Getting video data at {}x{} instead of the requested {}x{}, switching resolution.' .format(frame.size().width(), frame.size().height(), self.resolution.width(), self.resolution.height())) self._set_resolution(frame.size()) flip_x = self.flip_x.isChecked() # Only QR scan every QR_SCAN_PERIOD secs qr_scanned = time.time( ) - self.last_qr_scan_ts >= self.qrreader.interval() if qr_scanned: self.last_qr_scan_ts = time.time() # Crop the frame so we only scan a SCAN_SIZE rect frame_cropped = frame.copy(self.qr_crop) # Convert to Y800 / GREY FourCC (single 8-bit channel) # This creates a copy, so we don't need to keep the frame around anymore frame_y800 = frame_cropped.convertToFormat( QImage.Format_Grayscale8) # Read the QR codes from the frame self.qrreader_res = self.qrreader.read_qr_code( frame_y800.constBits().__int__(), frame_y800.byteCount(), frame_y800.bytesPerLine(), frame_y800.width(), frame_y800.height(), self.frame_id) # Call the validator to see if the scanned results are acceptable self.validator_res = self.validator.validate_results( self.qrreader_res) # Update the video overlay with the results self.video_overlay.set_results(self.qrreader_res, flip_x, self.validator_res) # Close the dialog if the validator accepted the result if self.validator_res.accepted: self.accept() return # Apply the crop blur effect if self.image_effect: frame = self.image_effect.apply(frame) # If horizontal flipping is enabled, only flip the display if flip_x: frame = frame.mirrored(True, False) # Display the frame in the widget self.video_widget.setPixmap(QPixmap.fromImage(frame)) self._update_stats(qr_scanned) def _init_stats(self): self.last_stats_time = time.perf_counter() self.frame_counter = 0 self.qr_frame_counter = 0 def _update_stats(self, qr_scanned): self.frame_counter += 1 if qr_scanned: self.qr_frame_counter += 1 now = time.perf_counter() last_stats_delta = now - self.last_stats_time if last_stats_delta > 1.0: # stats every 1.0 seconds fps = self.frame_counter / last_stats_delta qr_fps = self.qr_frame_counter / last_stats_delta if self.validator is not None: self.validator.strong_count = math.ceil( qr_fps / 3 ) # 1/3 of a second's worth of qr frames determines strong_count stats_format = 'running at {} FPS, scanner at {} FPS' self.logger.info(stats_format.format(fps, qr_fps)) self.frame_counter = 0 self.qr_frame_counter = 0 self.last_stats_time = now
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"))
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
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 Window(QWidget): # конструктор формы def __init__(self): super().__init__() self._Client = Biometric_Client( url='https://expasoft.com', port=2133, subscription_key='9fc9474b4bd16b492276eee41763a3cb') self.resize(800, 600) self.setObjectName("FormMain") self.setWindowTitle("БиоСКУД Archivist") self.labelHumans = QtWidgets.QLabel(self) self.labelHumans.setObjectName("labelHumans") self.labelHumans.setText("Профили сотрудников") self.labelHumans.setGeometry(QtCore.QRect(80, 15, 181, 21)) font = QtGui.QFont() font.setPointSize(12) self.labelHumans.setFont(font) self.labelPhotos = QtWidgets.QLabel(self) self.labelPhotos.setObjectName("labelPhotos") self.labelPhotos.setText("Фото сотрудника") self.labelPhotos.setGeometry(QtCore.QRect(390, 15, 181, 21)) font = QtGui.QFont() font.setPointSize(12) self.labelPhotos.setFont(font) self.listViewHumans = QtWidgets.QListWidget(self) self.listViewHumans.setObjectName("listViewHumans") self.listViewHumans.setGeometry(QtCore.QRect(10, 50, 291, 531)) self.listViewHumans.setIconSize(QtCore.QSize(200, 200)) self.listViewHumans.itemClicked.connect(self.LoadProfile) self.listViewPhotos = QtWidgets.QListWidget(self) self.listViewPhotos.setObjectName("listViewPhotos") self.listViewPhotos.setGeometry(QtCore.QRect(310, 50, 291, 281)) self.listViewPhotos.setIconSize(QtCore.QSize(150, 150)) self.labelName = QLabel(self) self.labelName.setText("ФИО:") self.labelName.move(310, 355) self.lineName = QLineEdit(self) self.lineName.resize(140, 25) self.lineName.move(350, 350) self.labelTag = QLabel(self) self.labelTag.setText("Пост:") self.labelTag.move(310, 385) self.lineTag = QLineEdit(self) self.lineTag.resize(140, 25) self.lineTag.move(350, 380) self.pushButtonAddProfile = QtWidgets.QPushButton(self) self.pushButtonAddProfile.setGeometry(QtCore.QRect(310, 420, 181, 51)) self.pushButtonAddProfile.setObjectName("pushButtonAddProfile") self.pushButtonAddProfile.setText("Добавить профиль") self.pushButtonAddProfile.clicked.connect(self.AddProfile) self.pushButtonUpdateProfile = QtWidgets.QPushButton(self) self.pushButtonUpdateProfile.setGeometry( QtCore.QRect(310, 475, 181, 51)) self.pushButtonUpdateProfile.setObjectName("pushButtonAddProfile") self.pushButtonUpdateProfile.setText("Обновить профиль") self.pushButtonUpdateProfile.clicked.connect(self.UpdateProfile) self.pushButtonDelProfile = QtWidgets.QPushButton(self) self.pushButtonDelProfile.setGeometry(QtCore.QRect(310, 530, 181, 51)) self.pushButtonDelProfile.setObjectName("pushButtonDelProfile") self.pushButtonDelProfile.setText("Удалить профиль") self.pushButtonDelProfile.clicked.connect(self.DelProfile) self.CameraStream = QVideoWidget(self) self.CameraStream.setObjectName("videoCameraStream") self.CameraStream.setGeometry(QtCore.QRect(610, 25, 180, 200)) self.device = QCamera.availableDevices()[0] self.camera = QCamera(self.device) self.camera.setViewfinder(self.CameraStream) self.camera.setCaptureMode(QCamera.CaptureStillImage) self.imageCapture = QCameraImageCapture(self.camera) self.imageCapture.imageSaved.connect(self.AddPhotoEnd) self.camera.start() self.pushButtonAddPhoto = QtWidgets.QPushButton(self) self.pushButtonAddPhoto.setObjectName("pushButtonAddPhoto") self.pushButtonAddPhoto.setText("Добавить фото") self.pushButtonAddPhoto.setGeometry(QtCore.QRect(610, 225, 181, 51)) self.pushButtonAddPhoto.clicked.connect(self.AddPhotoBegin) self.pushButtonDelPhoto = QtWidgets.QPushButton(self) self.pushButtonDelPhoto.setObjectName("pushButtonDelPhoto") self.pushButtonDelPhoto.setText("Удалить фото") self.pushButtonDelPhoto.setGeometry(QtCore.QRect(610, 280, 181, 51)) self.pushButtonDelPhoto.clicked.connect(self.DelPhoto) self.LoadProfiles() # загружаем список сотрудников def LoadProfiles(self): self.listViewHumans.clear() AllProfiles = self._Client.get_profiles_ids()['result'] if len(AllProfiles) != 0: for profile in AllProfiles: item = QtWidgets.QListWidgetItem() #item.setText(str(profile)) if (GetInfo(str(profile)) != None): item.setText(GetInfo(str(profile))["name"]) item.setToolTip(str(profile)) AllPhoto = self._Client.get_profile_images_ids( profile)['result'] if len(AllPhoto) != 0: FileName = "img/" + str(profile) + '-' + str( AllPhoto[0]) + '.jpg' self._Client.get_profile_image(profile, AllPhoto[0], FileName) item.setIcon(QtGui.QIcon(FileName)) self.listViewHumans.addItem(item) # загружаем профиль def LoadProfile(self, item): self.listViewPhotos.clear() #idProfile = int(item.text()) idProfile = int(item.toolTip()) AllPhoto = self._Client.get_profile_images_ids(idProfile)['result'] for photo in AllPhoto: FileName = "img/" + str(idProfile) + '-' + str(photo) + '.jpg' self._Client.get_profile_image(idProfile, photo, FileName) item = QtWidgets.QListWidgetItem() item.setText(str(photo)) item.setIcon(QtGui.QIcon(FileName)) self.listViewPhotos.addItem(item) infoProfile = JsonDataBase.GetInfo(idProfile) if infoProfile != None: self.lineName.setText(infoProfile['name']) self.lineTag.setText(infoProfile['tag']) else: self.lineName.setText("") self.lineTag.setText("") # добавляем профиль def AddProfile(self): profile_name = self.lineName.text() profile_post = self.lineTag.text() Id_Profile = self._Client.add_profile(profile_name, '01.01.1111', 'm', tags="").pop('result') JsonDataBase.AddInfo(Id_Profile, profile_name, '01.01.1111', "m", profile_post) self.LoadProfiles() # обновляем профиль def UpdateProfile(self): Id_Profile = self.listViewHumans.currentItem().toolTip() profile_name = self.lineName.text() profile_post = self.lineTag.text() if (JsonDataBase.GetInfo(Id_Profile) != None): JsonDataBase.UpdateInfo(Id_Profile, name=profile_name, tag=profile_post) else: JsonDataBase.AddInfo(Id_Profile, name=profile_name, tag=profile_post) self.LoadProfiles() # удаляем профиль def DelProfile(self): Id_Profile = self.listViewHumans.currentItem().toolTip() self._Client.delete_profile(Id_Profile) JsonDataBase.DelInfo(Id_Profile) self.LoadProfiles() # добавляем фото def AddPhotoBegin(self): if self.imageCapture.isReadyForCapture(): imgName = os.getcwd() + "\img\currentPhoto.jpg" self.camera.searchAndLock() self.imageCapture.capture(imgName) self.camera.unlock() def AddPhotoEnd(self): print(0) imgName = os.getcwd() + "\img\currentPhoto.jpg" imgName0 = os.getcwd() + "\img\currentPhoto0.jpg" idProfile = int(self.listViewHumans.currentItem().toolTip()) self._Client.get_aligned_faces(imgName, "img\currentPhoto") self._Client.enroll_profile_face(idProfile, imgName0) self.LoadProfile(self.listViewHumans.currentItem()) # удаляем фото def DelPhoto(self): #Id_Profile = self.listViewHumans.currentItem().text() Id_Profile = self.listViewHumans.currentItem().toolTip() Id_Photo = self.listViewPhotos.currentItem().text() self._Client.delete_image(Id_Profile, Id_Photo) self.LoadProfile(self.listViewHumans.currentItem())
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)
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)))
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()
class CameraMainWindow(QMainWindow): def __init__(self): super().__init__() uic.loadUi('MainWin.ui', self) self.setWindowTitle('CamPaint') self.setWindowIcon(QIcon('main_icon.ico')) self.setCentralWidget(self.tabWidget) # Загружаем камеру, холст, sql файл и задаем цвета кнопок self.load_cam() self.load_painter() self.load_sql() self.load_colors() def load_cam(self): self.cam_page.setLayout(self.cam_page_lay) self.error_cam.hide() self.camera = QCameraInfo.defaultCamera() # Проверяем, что камера сущетсвует # Если нет, то переключаемся на вторую вкладку if self.camera.isNull(): dialog = QErrorMessage() dialog.setWindowTitle('Warning') dialog.showMessage( 'Not enough cameras, the app will only be available in drawing mode' ) dialog.exec() self.error_cam.show() self.cam_page.setEnabled(False) self.tabWidget.setCurrentIndex(1) # Если да, то на первую else: self.tabWidget.setCurrentIndex(0) self.camera = QCamera(self.camera) self.view_cam = QCameraViewfinder(self) self.view_cam.setMediaObject(self.camera) self.view_cam.setAutoFillBackground(True) self.camera.setViewfinder(self.view_cam) self.box_lay = QVBoxLayout(self) self.box_lay.addWidget(self.view_cam) self.scrolling.setLayout(self.box_lay) # Запускаем камеру self.camera.start() # Подвязываем кнопку к слоту со снимком self.bt_cam.clicked.connect(self.make_ph) # Можно зумить фотографию self.zoom.valueChanged.connect(self.zoom_pict) def make_ph(self): self.camera.setCaptureMode(QCamera.CaptureStillImage) self.capt = QCameraImageCapture(self.camera) # Останавливаем съемку self.camera.searchAndLock() # Вызываем диалог и иохранением файла dial = QFileDialog.getSaveFileName( self, 'Save file', '', 'Картинка (*.jpg);;Картинка (*.png);;Все файлы (*)')[0] if dial: self.capt.capture(dial) self.camera.unlock() def zoom_pict(self, value): # Вычисляем зум камеры по функции zoom=1.0 + value * 3 / 99 # 1.0 - обязательный параметр QCameraFocus.zoomTo(self.camera.focus(), 1.0 + value * 3 / 99, 1.0) def load_painter(self): # Загружаем холст self.paint_page.setLayout(self.paint_page_lay) # Текущий цвет - черный, ширина кисти - 10 self.now_col = QColor(0, 0, 0) self.now_width = 10 self.point_width.setValue(10) # Подвязываем кнопку с изменением ширины кисти к соответсвующему слоту self.point_width.valueChanged.connect(self.change_width) # Создаем холст как экземпляр класса Canvas из доп.модуля Canvas self.canvas = Canvas.Canvas(self.main_paint_widg) self.canvas.move(1, 1) self.canvas.resize(self.main_paint_widg.width() - 1, self.main_paint_widg.height() - 1) print(self.main_paint_widg.size(), self.canvas.size(), self.border_lab.size()) # Устанавливаем границы рамки self.border_lab.setStyleSheet( 'border-style: solid; border-width: 2px; border-color: black;') self.canvas.setStyleSheet('background-color: white;') # Устанавливаем сильный фокус для перехвата всех событий # клавиатуры и мыши self.setFocusPolicy(Qt.StrongFocus) # Подвязываем действия из меню к слотам self.actionSave.triggered.connect(self.save_file) self.actionSave_as.triggered.connect(self.save_as_file) self.actionOpen.triggered.connect(self.open_file) self.actionReference.triggered.connect(self.open_reference) # и кнопку очистки холста, а также задания цвета кисти self.bt_clear.clicked.connect(self.clear_canvas) self.bt_set_color.clicked.connect(self.set_color_with_bt) # Имя файла изначально не задано, файл не сохранен self.file_name = '' self.saved = False self.resizeEvent(QResizeEvent(self.size(), self.size())) def change_width(self, value): self.now_width = value def keyPressEvent(self, event): # Обрабатываем события клавитатуры if int(event.modifiers()) == Qt.CTRL and event.key() == Qt.Key_Z: # Функция 'назад', удаляем все объекты, которые нарисовали if self.canvas.obj: del self.canvas.obj[-1] self.canvas.update() elif int(event.modifiers()) == Qt.CTRL and event.key() == Qt.Key_S: # Функция 'сохранить', сохраняем файл, если есть изменения if self.canvas.obj: self.save_file() elif int(event.modifiers()) == Qt.CTRL and event.key() == Qt.Key_O: # Функция 'открыть', открываем файл self.open_file() elif int(event.modifiers()) == Qt.CTRL and event.key() == Qt.Key_H: # Функция 'справка', открываем справку self.open_reference() def resizeEvent(self, event): # При изменении размеров окна, устанавливаем соответствующие размеры холста и рамки self.canvas.resize(self.main_paint_widg.width() - 1, self.main_paint_widg.height() - 1) self.border_lab.resize(self.main_paint_widg.width(), self.main_paint_widg.height()) def save_as_file(self): # Сохранение файла как dial = \ QFileDialog.getSaveFileName(self, 'Save file as', '', 'Картинка (*.jpg);;Картинка (*.png);;Все файлы (*)')[ 0] if dial: # Захватываем изображжение с холста и сохраняем pixmap = QPixmap(self.canvas.grab()) pixmap.save(dial) # Сохраняем имя файла в переменной self.file_name, чтобы использовать в функции save_file # Очищаем нарисованные объекты, так как уже их сохранили self.file_name = dial self.saved = True self.canvas.obj = [] def save_file(self): # Если имя файла выбрано, просто сохраняем if self.file_name: pixmap = QPixmap(self.canvas.grab()) pixmap.save(self.file_name) self.saved = True self.canvas.obj = [] # В ином случае, сохраняем как else: self.save_as_file() def open_file(self): # Открываем новый файл dial = QFileDialog.getOpenFileName( self, 'Open file', '', 'Картинка (*.jpg);;Картинка (*.png);;Все файлы (*)')[0] if dial: # Если старый файл не сохранен, предлагаем сохранить его if self.canvas.obj and not self.saved: dial2 = Dialogs.Message() res = dial2.exec() if res == dial2.Save: self.save_file() if res == dial2.Cancel: pass # Сохраняем новое имя файла, вызываем функцию open_file в экземпляре холста self.file_name = dial self.canvas.obj = [] self.canvas.open_file() def open_reference(self): dial = Dialogs.Reference() dial.exec() def clear_canvas(self): # Очищаем нарисованные объекты self.canvas.obj.clear() self.canvas.update() def set_color(self, color): # Устанавливаем текущий цвет self.now_col = color red, green, blue = color.red(), color.green(), color.blue() # Подключаемся к базе данных в папке проекта # и добавляем его к любимым цветам пользователя con = sqlite3.connect('own_colors_db.db') cur = con.cursor() colors = cur.execute( f'''SELECT * from colors WHERE red={red} and green={green} and blue={blue}''' ).fetchall() if colors: id = colors[0][0] cur.execute( f'''UPDATE colors SET counts=counts + 1 WHERE id={id}''') else: last_id = cur.execute( f'''SELECT id from colors''').fetchall()[-1][0] cur.execute( f'''INSERT INTO colors VALUES ({last_id + 1}, {red}, {green}, {blue}, 1)''' ) con.commit() con.close() def set_color_with_bt(self): # Слот для кнопки выбора цвета color = QColorDialog.getColor() self.set_color(color) def closeEvent(self, event): # Закрываем файл, обнуляя значение зума self.zoom.setValue(1) # И предлагаем сохранить файл, если он не сохранен if self.canvas.obj and not self.saved: dial = Dialogs.Message() res = dial.exec() if res == dial.Save: self.save_file() if res == dial.Cancel: event.ignore() def load_sql(self): # При отсутствии цветов в базе данных(в первом открытии приложения) # добавляем в базу данных новый цвет - черный con = sqlite3.connect('own_colors_db.db') cur = con.cursor() len_sql = len(cur.execute(f'''SELECT * from colors''').fetchall()) if len_sql == 0: cur.execute('''INSERT INTO colors VALUES (1, 0, 0, 0, 1)''') con.commit() con.close() def load_colors(self): # Загружаем цвета в кнопки любимых цветов пользователя colors = [] con = sqlite3.connect('own_colors_db.db') cur = con.cursor() ex_colors = sorted(cur.execute( '''SELECT red, green, blue, counts from colors''').fetchall(), key=lambda i: i[3])[:21] ex_colors = [(i[0], i[1], i[2]) for i in ex_colors] colors.extend(ex_colors) # Если цветов недостаточно, заполняем кнопки случайными цветами # вдруг какой-нибудь из них ползователю понравится if len(colors) < 20: for i in range(20 - len(colors)): new_color = (randrange(256), randrange(256), randrange(256)) while new_color in colors: new_color = (randrange(256), randrange(256), randrange(256)) colors.append(new_color) # Сохраняем цвета кнопок в словарь, где ключ - кнопка, значение - цвет # А также подключаем кнопки к слоту и изменением цвета self.bt_colors_dict = {} for i in range(4): for j in range(5): exec( f'self.bt{i}{j}.setStyleSheet("background:rgb({colors[0][0]}, {colors[0][1]}, {colors[0][2]});")' ) color = QColor(colors[0][0], colors[0][1], colors[0][2]) exec(f'self.bt_colors_dict[self.bt{i}{j}] = color') exec(f'self.bt{i}{j}.clicked.connect(self.set_color_with_bts)') del colors[0] def set_color_with_bts(self): # Слот для установки цвета кисти self.set_color(self.bt_colors_dict[self.sender()])
class VegaMainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) if len(QCameraInfo.availableCameras()) == 0: QMessageBox.warning( self, 'Camera not found', 'You don\'t have any cameras on your computer so you can\'t use this app...\nBuy a new camera (╯°^°)╯┻━┻', QMessageBox.Ok) exit(-1) self.central_widget = QWidget(self) self.main_grid = QGridLayout(self.central_widget) self.option_group = QGroupBox(None) self.group_grid = QGridLayout(self.option_group) self.addr_msg = QLabel('Database addr') self.camera_msg = QLabel('Camera') self.camera_combo = QComboBox() self.addr_edit = QLineEdit() self.camera_place = QGroupBox(None) self.auth_btn = QPushButton('Log in') self.camera_grid = QGridLayout(self.camera_place) self.camera_widget = QCameraViewfinder() self.camera_obj = QCamera(QCameraInfo.defaultCamera()) self.veg_cfg = Config() def createUI(self): self.setWindowIcon(QIcon(QPixmap(':/kimp_img/vega.png'))) self.setStyleSheet(styles.global_css) self.setWindowTitle('Vega') self.camera_grid.addWidget(self.camera_widget, 0, 0, 5, 5) self.camera_place.setTitle('Camera') self.main_grid.addWidget(self.camera_place, 2, 0, 5, 5) self.camera_obj.setViewfinder(self.camera_widget) self.main_grid.addWidget(self.auth_btn, 7, 0, 1, 5) self.central_widget.setLayout(self.main_grid) self.setCentralWidget(self.central_widget) self.show() def initValues(self): self.addr_edit.setText(self.veg_cfg.get_db_addr()) self.camera_obj.setCaptureMode(QCamera.CaptureStillImage) if self.veg_cfg.get_debug() == True: self.group_grid.addWidget(self.addr_msg, 0, 0, 1, 2) self.group_grid.addWidget(self.camera_msg, 1, 0, 1, 2) self.addr_edit.setAlignment(Qt.AlignRight) self.group_grid.addWidget(self.addr_edit, 0, 2, 1, 5) for i in QCameraInfo.availableCameras(): self.camera_combo.addItem(i.deviceName()) self.camera_combo.setCurrentText( QCameraInfo.defaultCamera().deviceName()) self.group_grid.addWidget(self.camera_combo, 1, 2, 1, 5) self.option_group.setTitle('Option') self.main_grid.addWidget(self.option_group, 0, 0, 2, 5) else: self.option_group.hide() def connectSignals(self): self.auth_btn.clicked.connect(self.onLogInClicked) def cameraStart(self): if self.camera_obj.status() != QCamera.UnavailableStatus: print('Camera started') self.camera_obj.start() @pyqtSlot() def onLogInClicked(self): capture = QCameraImageCapture(self.camera_obj) capture.capture(__file__[:-14:] + 'capture.jpg') sleep(1) s_data = {'image': open(__file__[:-14:] + 'capture.jpg', 'rb')} r = requests.post(self.veg_cfg.get_db_addr(), files=s_data) if r.json()['status'] != 'ok': QMessageBox.warning( self, 'Verification failed', 'Failed to pass identity verification.\nTry again or cantact your admin (╯°^°)╯┻━┻', QMessageBox.Ok) else: if self.veg_cfg.get_browser() == 'firefox': fire = auth.FirefoxAuth(r.json()['login'], r.json()['passwd']) fire.get_auth_token() else: chrome = auth.ChromeAuth(r.json()['login'], r.json()['passwd']) chrome.get_auth_token()
class 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)
class Camera(QObject): def __init__(self, parent=QObject()): super(Camera, self).__init__(parent) # chooses the system default camera self.cam = QCamera() self.imageCapture = QCameraImageCapture(self.cam) self.caminfo = QCameraInfo(self.cam) self.camvfind = QCameraViewfinder() self.camvfindset = QCameraViewfinderSettings() self.recorder = QMediaRecorder(self.cam) def init_camera(self): cameras = QCameraInfo.availableCameras() for cameraInfo in cameras: # select the capturing device if it is available if cameraInfo.description().find("Capture") is not -1: self.cam = QCamera(cameraInfo) self.caminfo = QCameraInfo(self.cam) self.recorder = QMediaRecorder(self.cam) print("Camera Chosen: " + self.caminfo.description()) print(self.cam.supportedViewfinderFrameRateRanges()) self.cam.setCaptureMode(QCamera.CaptureStillImage) if self.cam.isCaptureModeSupported(QCamera.CaptureStillImage): print("Capturemode supported") self.cam.load() self.cam.setViewfinder(self.camvfind) self.cam.start() self.imageCapture = QCameraImageCapture(self.cam) self.imageCapture.setCaptureDestination( QCameraImageCapture.CaptureToBuffer) def capture_still(self): self.imageCapture.capture() def setOnCapture(self, callback=None): self.imageCapture.imageCaptured.connect(callback) def start_vid(self): self.cam.load() # self.camvfind.show() self.cam.setViewfinder(self.camvfind) self.cam.setCaptureMode(QCamera.CaptureVideo) self.cam.start() audio = QAudioEncoderSettings() audio.setCodec("audio/amr") audio.setQuality(QtMultimedia.QMultimedia.NormalQuality) video = QVideoEncoderSettings() # video.setCodec("video/mp4") video.setQuality(QtMultimedia.QMultimedia.NormalQuality) video.setResolution(1920, 1080) video.setFrameRate(30.0) # self.recorder.setAudioSettings(audio) self.recorder.setVideoSettings(video) self.recorder.setContainerFormat("mp4") print("Output Loc: " + str(self.recorder.outputLocation())) def start_recording(self): directory = os.path.abspath(str(os.getcwd())) filename = "test" + str(time.time()) + ".mp4" abs_path = os.path.join(directory, filename) self.recorder.setOutputLocation(QUrl(abs_path)) self.recorder.record() def stop_recording(self): self.recorder.stop()
class CameraController(PopupToolButton): def __init__(self, parent=None): super(CameraController, self).__init__(icon=getIcon('camera.png'), mode=QToolButton.InstantPopup, parent=parent) self.setToolTip(iWebcamIpfsCapture()) self.menuDevices = QMenu(iDevices()) self.menuDevices.setIcon(self.icon()) self.menu.addMenu(self.menuDevices) self.menu.addSeparator() self.captureAction = QAction(self.icon(), iCapture(), self, triggered=self.onCameraView) self.captureAction.setEnabled(False) self.menu.addAction(self.captureAction) self.camView = None self.videoDevicesGroup = QActionGroup(self) self.videoDevicesGroup.setExclusive(True) self.detectDevices() def detectDevices(self): cameraDevice = QByteArray() for name in QCamera.availableDevices(): description = QCamera.deviceDescription(name) deviceAction = QAction(description, self.videoDevicesGroup) deviceAction.setCheckable(True) deviceAction.setData(name) if cameraDevice.isEmpty(): cameraDevice = name deviceAction.setChecked(True) self.menuDevices.addAction(deviceAction) self.videoDevicesGroup.triggered.connect(self.changeCameraDevice) self.setCamera(cameraDevice) def changeCameraDevice(self, action): cameraName = action.data() log.debug(f'Using camera: {cameraName}') self.setCamera(cameraName) def setCamera(self, cameraDevice): if cameraDevice.isEmpty(): self.camera = QCamera() else: self.camera = QCamera(cameraDevice) self.captureAction.setEnabled(True) def onCameraView(self): if self.camView and self.camView.isVisible(): return if self.camView: self.camView.close() del self.camView self.camView = CameraView(self.camera) self.camera.setViewfinder(self.camView.ui.viewfinder) self.camView.show() self.camera.start()