Search code examples
androidqtcameraqmlqtmultimedia

Using Camera on Linux Desktop in Qt Quick


I have a simple project in Qt Quick in which I need to process output from camera. The project should run on Android, Windows and Linux. So far I am successful in connecting to the camera on Android, but not on Linux.

My setup is as follows:

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

main.qml

import QtQuick 2.9
import QtQuick.Controls 2.2
import QtMultimedia 5.9

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("EyeGaze")

    SwipeView {
        id: swipeView
        anchors.fill: parent
        currentIndex: tabBar.currentIndex

        CameraViewForm {}

        AboutForm {}
    }

    footer: TabBar {
        id: tabBar
        currentIndex: swipeView.currentIndex

        TabButton {
            text: qsTr("Main")
        }
        TabButton {
            text: qsTr("About")
        }
    }
}

CameraViewForm.qml

import QtQuick 2.9
import QtQuick.Controls 2.2
import QtMultimedia 5.9

Page {
    width: 600
    height: 400

    header: Label {
        text: qsTr("Camera View")
        horizontalAlignment: Text.AlignHCenter
        font.pixelSize: Qt.application.font.pixelSize * 2
        padding: 10
    }

    Camera {
           id: camera
           position: Camera.FrontFace
       }

       VideoOutput {
           source: camera
           anchors.fill: parent
           focus: visible // to receive focus and capture key events when visible
       }
}

I am getting CameraBin error: "Could not read from resource." and a blank screen in the Camera View.

I tried checking camera availability from C++ code (using QCameraInfo::availableCameras()) and I found out that my laptop does indeed have a webcam at /dev/video0 which the program seems to be able to access.

Am I accessing the camera wrong? Should I do it from C++ code, not QML?


Solution

  • Actually, your code should work (at least it works on my side). Here are few hints.

    First of all, check if anything is already using your webcam:

    lsof /dev/video0
    

    and

    fuser /dev/video0
    

    If no output -- great, move on. Otherwise, check what is happening with your webcam and who is actually using it.


    Check what are the permissions for webcam:

    ls -la /dev/video0
    

    It could be something like:

    crw-rw----+ 1 root video 81, 0 тра 10 13:38 /dev/video0
    

    Check if your user is in video group, otherwise, add it by

    adduser YOUR_USER video
    

    Hope this helps!