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 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()
def main(): app = QApplication( sys.argv ) # must be called in order to be able to use all the stuff below(!) print("The application is executed on: %s" % app.platformName()) l_cameras = QCameraInfo.availableCameras() if len(l_cameras) == 0: print("ERROR: no cameras found") sys.exit(-1) else: print("INFO: found %i camera(s)" % len(l_cameras)) print() for i_idx, oc_caminfo in enumerate(l_cameras): # QCameraInfo - derived properties print("Camera #%i:" % i_idx) print("\t deviceName: %s" % oc_caminfo.deviceName()) print("\t description: %s" % oc_caminfo.description()) print("\t isNull: %s" % oc_caminfo.isNull()) print("\t orientation: %s" % oc_caminfo.orientation()) print("\t position: %s" % oc_caminfo.position()) # QCamera - derived properties oc_camera = QCamera(i_idx) camera_sync_load_and_start(oc_camera) oc_camera_exposure = oc_camera.exposure() print("\t captureMode: %s" % captureMode2str(oc_camera.captureMode())) print("\t exposure:") print("\t\t isAvailabe: %s" % oc_camera_exposure.isAvailable()) if oc_camera_exposure.isAvailable(): print("\t\t aperture: %s" % oc_camera_exposure.aperture()) # TODO test this, add more entries oc_camera_focus = oc_camera.focus() print("\t focus:") print("\t\t isAvailabe: %s" % oc_camera_focus.isAvailable()) if oc_camera_focus.isAvailable(): print("\t\t aperture: %f" % oc_camera_focus.digitalZoom()) # TODO test this, add more entries oc_cam_img_proc = oc_camera.imageProcessing() print("\t imageProcessing:") print("\t\t isAvailabe: %s" % oc_cam_img_proc.isAvailable()) if oc_cam_img_proc.isAvailable(): print("\t\t brightness: %f" % oc_cam_img_proc.brightness()) print("\t\t contrast: %f" % oc_cam_img_proc.contrast()) print("\t\t denoisingLevel: %f" % oc_cam_img_proc.denoisingLevel()) print("\t\t manualWhiteBalance: %f" % oc_cam_img_proc.manualWhiteBalance()) print("\t\t saturation: %f" % oc_cam_img_proc.saturation()) print("\t\t sharpeningLevel: %f" % oc_cam_img_proc.sharpeningLevel()) print("\t isVideoCaptureSupported: %s" % oc_camera.isCaptureModeSupported(QCamera.CaptureVideo)) print("\t lockStatus: %s" % lockStatus2str(oc_camera.lockStatus())) print("\t requestedLocks: %s" % lockType2str(oc_camera.requestedLocks())) print("\t state: %s" % state2str(oc_camera.state())) print("\t status: %s" % status2str(oc_camera.status())) print("\t supportedLocks: %s" % lockType2str(oc_camera.supportedLocks())) print( "\t supportedViewfinderFrameRateRanges: %s" % frameRateRange2str(oc_camera.supportedViewfinderFrameRateRanges())) print("\t supportedViewfinderPixelFormats: %s" % repr(oc_camera.supportedViewfinderPixelFormats())) print("\t supportedViewfinderResolutions: \n\t\t%s" % frameResolution2str(oc_camera.supportedViewfinderResolutions())) print("\t len(supportedViewfinderSettings): %s" % len(oc_camera.supportedViewfinderSettings())) # QCameraViewfinderSettings - derived properties oc_vf_settings = oc_camera.viewfinderSettings() if oc_vf_settings.isNull(): print("\t viewfinderSettings: not supported") camera_sync_stop_and_unload(oc_camera) print() continue print("\t maximumFrameRate: %f" % oc_vf_settings.maximumFrameRate()) print("\t minimumFrameRate: %f" % oc_vf_settings.minimumFrameRate()) print("\t resolution: %s" % frameResolution2str([oc_vf_settings.resolution()])) # TODO the rest of methods... camera_sync_stop_and_unload(oc_camera) print()
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(QWidget): def __init__(self, parent=None, standalone=False): super(Camera, self).__init__(parent) # This prevents doing unneeded initialization # when QtDesginer loads the plugin. if parent is None and not standalone: return if not multimedia_available: return self.ui = uic.loadUi(os.path.join(WIDGET_PATH, "camera.ui"), self) self.camera = None self.imageCapture = None self.mediaRecorder = None self.isCapturingImage = False self.applicationExiting = False self.imageSettings = QImageEncoderSettings() self.audioSettings = QAudioEncoderSettings() self.videoSettings = QVideoEncoderSettings() self.videoContainerFormat = '' camera_device = QByteArray() videoDevicesGroup = QActionGroup(self) videoDevicesGroup.setExclusive(True) if not QCamera.availableDevices(): self.ui.devicesCombo.addItem("No Device") else: for deviceName in QCamera.availableDevices(): description = QCamera.deviceDescription(deviceName) self.ui.devicesCombo.addItem(description) videoDeviceAction = QAction(description, videoDevicesGroup) videoDeviceAction.setCheckable(True) videoDeviceAction.setData(deviceName) if camera_device.isEmpty(): cameraDevice = deviceName videoDeviceAction.setChecked(True) self.ui.devicesCombo.addAction(videoDeviceAction) videoDevicesGroup.triggered.connect(self.updateCameraDevice) self.ui.captureWidget.currentChanged.connect(self.updateCaptureMode) self.ui.devicesCombo.currentIndexChanged.connect( self.get_device_action) self.ui.lockButton.hide() # Start camera 2s after the UI has loaded QTimer.singleShot(2000, lambda: self.setCamera(camera_device)) def setCamera(self, cameraDevice): try: if cameraDevice.isEmpty(): self.camera = QCamera() else: self.camera = QCamera(cameraDevice) self.camera.stateChanged.connect(self.updateCameraState) self.camera.error.connect(self.displayCameraError) self.mediaRecorder = QMediaRecorder(self.camera) self.mediaRecorder.stateChanged.connect(self.updateRecorderState) self.imageCapture = QCameraImageCapture(self.camera) self.mediaRecorder.durationChanged.connect(self.updateRecordTime) self.mediaRecorder.error.connect(self.displayRecorderError) self.mediaRecorder.setMetaData(QMediaMetaData.Title, "Camera Widget") self.ui.exposureCompensation.valueChanged.connect( self.setExposureCompensation) self.camera.setViewfinder(self.ui.viewfinder) self.updateCameraState(self.camera.state()) self.updateLockStatus(self.camera.lockStatus(), QCamera.UserRequest) self.updateRecorderState(self.mediaRecorder.state()) self.imageCapture.readyForCaptureChanged.connect( self.readyForCapture) self.imageCapture.imageCaptured.connect(self.processCapturedImage) self.imageCapture.imageSaved.connect(self.imageSaved) self.camera.lockStatusChanged.connect(self.updateLockStatus) self.ui.captureWidget.setTabEnabled( 0, self.camera.isCaptureModeSupported(QCamera.CaptureStillImage)) self.ui.captureWidget.setTabEnabled( 1, self.camera.isCaptureModeSupported(QCamera.CaptureVideo)) self.updateCaptureMode() self.camera.start() except: pass def keyPressEvent(self, event): if event.isAutoRepeat(): return if event.key() == Qt.Key_CameraFocus: self.displayViewfinder() self.camera.searchAndLock() event.accept() elif event.key() == Qt.Key_Camera: if self.camera.captureMode() == QCamera.CaptureStillImage: self.takeImage() elif self.mediaRecorder.state() == QMediaRecorder.RecordingState: self.stop() else: self.record() event.accept() else: super(Camera, self).keyPressEvent(event) def keyReleaseEvent(self, event): if event.isAutoRepeat(): return if event.key() == Qt.Key_CameraFocus: self.camera.unlock() else: super(Camera, self).keyReleaseEvent(event) def updateRecordTime(self): msg = "Recorded {} sec".format(self.mediaRecorder.duration()) self.ui.timeLabel.text = msg print(msg) def processCapturedImage(self, requestId, img): scaledImage = img.scaled(self.ui.viewfinder.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.ui.lastImagePreviewLabel.setPixmap(QPixmap.fromImage(scaledImage)) self.displayCapturedImage() QTimer.singleShot(4000, self.displayViewfinder) def configureSettings(self): settings_dialog = Settings(self.mediaRecorder, self.imageCapture) settings_dialog.setImageSettings(self.imageSettings) settings_dialog.setAudioSettings(self.audioSettings) settings_dialog.setVideoSettings(self.videoSettings) settings_dialog.setFormat(self.videoContainerFormat) # settings_dialog.setStreamingSettings(self.streamingSettings) if settings_dialog.exec_(): self.imageSettings = settings_dialog.imageSettings() self.audioSettings = settings_dialog.audioSettings() self.videoSettings = settings_dialog.videoSettings() self.videoContainerFormat = settings_dialog.format() self.imageCapture.setEncodingSettings(self.imageSettings) self.mediaRecorder.setEncodingSettings(self.audioSettings, self.videoSettings, self.videoContainerFormat) def record(self): self.mediaRecorder.record() self.updateRecordTime() def pause(self): self.mediaRecorder.pause() def stop(self): self.mediaRecorder.stop() def setMuted(self, muted): self.mediaRecorder.setMuted(muted) def toggleLock(self): if self.camera.lockStatus() in (QCamera.Searching, QCamera.Locked): self.camera.unlock() elif self.camera.lockStatus() == QCamera.Unlocked: self.camera.searchAndLock() def updateLockStatus(self, status, reason): indicationColor = Qt.black if status == QCamera.Searching: self.ui.statusbar.showMessage("Focusing...") self.ui.lockButton.setText("Focusing...") indicationColor = Qt.yellow elif status == QCamera.Locked: self.ui.lockButton.setText("Unlock") self.ui.statusbar.showMessage("Focused", 2000) indicationColor = Qt.darkGreen elif status == QCamera.Unlocked: self.ui.lockButton.setText("Focus") if reason == QCamera.LockFailed: self.ui.statusbar.showMessage("Focus Failed", 2000) indicationColor = Qt.red palette = self.ui.lockButton.palette() palette.setColor(QPalette.ButtonText, indicationColor) self.ui.lockButton.setPalette(palette) def takeImage(self): self.isCapturingImage = True self.imageCapture.capture() def startCamera(self): self.camera.start() def stopCamera(self): self.camera.stop() def updateCaptureMode(self): tabIndex = self.ui.captureWidget.currentIndex() captureMode = QCamera.CaptureStillImage if tabIndex == 0 else QCamera.CaptureVideo if self.camera.isCaptureModeSupported(captureMode): self.camera.setCaptureMode(captureMode) def updateCameraState(self, state): if state == QCamera.ActiveState: self.ui.actionStartCamera.setEnabled(False) self.ui.actionStopCamera.setEnabled(True) self.ui.captureWidget.setEnabled(True) self.ui.actionSettings.setEnabled(True) elif state in (QCamera.UnloadedState, QCamera.LoadedState): self.ui.actionStartCamera.setEnabled(True) self.ui.actionStopCamera.setEnabled(False) self.ui.captureWidget.setEnabled(False) self.ui.actionSettings.setEnabled(False) def updateRecorderState(self, state): if state == QMediaRecorder.StoppedState: self.ui.recordButton.setEnabled(True) self.ui.pauseButton.setEnabled(True) self.ui.stopButton.setEnabled(False) elif state == QMediaRecorder.PausedState: self.ui.recordButton.setEnabled(True) self.ui.pauseButton.setEnabled(False) self.ui.stopButton.setEnabled(True) elif state == QMediaRecorder.RecordingState: self.ui.recordButton.setEnabled(False) self.ui.pauseButton.setEnabled(True) self.ui.stopButton.setEnabled(True) def setExposureCompensation(self, index): self.camera.exposure().setExposureCompensation(index * 0.5) def displayRecorderError(self): QMessageBox.warning(self, "Capture error", self.mediaRecorder.errorString()) def displayCameraError(self): QMessageBox.warning(self, "Camera error", self.camera.errorString()) def get_device_action(self, index): self.ui.devicesCombo.actions()[index].trigger() def updateCameraDevice(self, action): self.setCamera(action.data()) def displayViewfinder(self): self.ui.stackedWidget.setCurrentIndex(0) def displayCapturedImage(self): self.ui.stackedWidget.setCurrentIndex(1) def readyForCapture(self, ready): self.ui.takeImageButton.setEnabled(ready) def imageSaved(self, id, fileName): self.isCapturingImage = False if self.applicationExiting: self.close() def closeEvent(self, event): if self.isCapturingImage: self.setEnabled(False) self.applicationExiting = True event.ignore() else: event.accept()