08.05.2018       Выпуск 229 (07.05.2018 - 13.05.2018)       Статьи

NSAViewer - работаем с камерой из Qt

Открываем вебкамеру, делаем фото

Читать>>



Экспериментальная функция:

Ниже вы видите текст статьи по ссылке. По нему можно быстро понять ссылка достойна прочтения или нет

Просим обратить внимание, что текст по ссылке и здесь может не совпадать.

This app isn't actually a direct line from your webcam to the NSA, it's a demo of using the webcam/camera support in Qt. The name is a nod to the paranoia (or is it...) of being watched through your webcam by government spooks.

I did consider making the app (openly) upload snapshots of users to a remote server to complete the idea. But this is the internet, and I don't want to see any of you naked.

NSAViewer

With this app you can use your laptop's built-in camera to view yourself, and take photobooth-style snapshots. The app uses Qt's built in webcam methods to provide support for multiple cameras if you have them.

Camera Initialisation

Camera support in Qt5 is accessible via QtMultimedia with multimedia-specific widgets available via QtMultimediaWidgets. The first step to using cameras is to get a list of currently available cameras on the system, via QCameraInfo.availableCameras(). This returns a list of QCameraInfo objects, which provide various bits of information about each camera, including a unique ID.

If we have no cameras available we just quit out, ungracefully. If a camera is available we setup the QCameraViewfinder to provide a live updating viewfinder view from the active camera. We select the first camera in our list to use as a 'default' — on a laptop this is usually the built in camera.

class MainWindow(QMainWindow):

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

    self.available_cameras = QCameraInfo.availableCameras()
    if not self.available_cameras:
        pass #quit

    self.viewfinder = QCameraViewfinder()
    self.viewfinder.show()
    self.setCentralWidget(self.viewfinder)

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

The toolbar users a user to select the active camera, take snapshot photos and to select the output folder for these photos. Each QAction is connected to a custom slot to handle the specific behaviour.

The camera selection list is pre-filled with the user-friendly name of each camera, via QCameraInfo.description(). The index of the selected camera in the combobox matches its position in the list.

    # Setup tools
    camera_toolbar = QToolBar("Camera")
    camera_toolbar.setIconSize(QSize(14, 14))
    self.addToolBar(camera_toolbar)

    photo_action = QAction(QIcon(os.path.join('images', 'camera-black.png')), "Take photo...", self)
    photo_action.setStatusTip("Take photo of current view")
    photo_action.triggered.connect(self.take_photo)
    camera_toolbar.addAction(photo_action)

    change_folder_action = QAction(QIcon(os.path.join('images', 'blue-folder-horizontal-open.png')), "Change save location...", self)
    change_folder_action.setStatusTip("Change folder where photos are saved.")
    change_folder_action.triggered.connect(self.change_folder)
    camera_toolbar.addAction(change_folder_action)

    camera_selector = QComboBox()
    camera_selector.addItems([c.description() for c in self.available_cameras])
    camera_selector.currentIndexChanged.connect( self.select_camera )

    camera_toolbar.addWidget(camera_selector)

Camera selection

The camera select method accepts a single parameter i, which is the index of a camera in our prefilled self.available_cameras list. This is a QCameraInfo object, which can be passed to QCamera to create a new camera object.

Once the camera object is created, we set it to use our existing viewfinder widget (central widget). The capture mode is set to QCamera.CaptureStillImage and then the camera must be started with .start().

Capture of images from a camera is handled by QCameraImageCapture, which we setup by passing in our previously created camera object. The .imageCaptured signal is triggered every time (after) an image is captured, so we can connect to it to show a status update — the snapshotting is done seperately.

def select_camera(self, i):
    self.camera = QCamera(self.available_cameras[i])
    self.camera.setViewfinder(self.viewfinder)
    self.camera.setCaptureMode(QCamera.CaptureStillImage)
    self.camera.error.connect(lambda: self.alert(self.camera.errorString()))
    self.camera.start()

    self.capture = QCameraImageCapture(self.camera)
    self.capture.error.connect(lambda i, e, s: self.alert(s))
    self.capture.imageCaptured.connect(lambda d, i: self.status.showMessage("Image %04d captured" % self.save_seq))

    self.current_camera_name = self.available_cameras[i].description()
    self.save_seq = 0

Ready to build your own apps?

Create Simple GUI Applications with Python & Qt is my beginners guide to building cross-platform GUI applications with Python. In this book I take you step by step from displaying your first window, to fully functional software.

Take photo

Taking a camera snapshot is handled in our custom take_photo slot using the QCameraImageCapture object created when initialising the camera. The .capture() method accepts a filename, which we create using our selected save path and a full-name timestamp. The file is stamped with a current time, plus the current camera and a sequence number to avoid conflicts. Snapshots are saved in JPEG format.

def take_photo(self):
    timestamp = time.strftime("%d-%b-%Y-%H_%M_%S")
    self.capture.capture(os.path.join(self.save_path, "%s-%04d-%s.jpg" % (
        self.current_camera_name,
        self.save_seq,
        timestamp
    )))
    self.save_seq += 1

The sequence number is incremented after the snapshot is taken.



Лучшая Python рассылка



Разместим вашу рекламу

Пиши: mail@pythondigest.ru

Нашли опечатку?

Выделите фрагмент и отправьте нажатием Ctrl+Enter.

Система Orphus