Пример #1
0
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()
Пример #2
0
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()
Пример #3
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

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

        toolBar = QToolBar()


        self.addToolBar(toolBar)

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

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

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

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


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




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

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


    def predicition(self,filename):

        model = resnet50.ResNet50()

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


        x = image.img_to_array(img)


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


        x = resnet50.preprocess_input(x)


        predictions = model.predict(x)

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

        top_value = []

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

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


    def createAudio(self,text):

        language = 'en'

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

        myobj.save(text+".mp3")

        return text+".mp3"


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

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

    def imageSaved(self, id, fileName):

        predicitionName = self.predicition(fileName)

        audiofile = self.createAudio(predicitionName)

        index = self.tabWidget.count()

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

        self.tabWidget.addTab(imageView, predicitionName)
        self.tabWidget.setCurrentIndex(index)