ImageAcquisition.cpp 11.8 KB
Newer Older
Thiago C. Santini's avatar
Thiago C. Santini committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
#include "ImageAcquisition.h"

#include <QThread>

static bool isMaster(string str)
{
    if (settings.value("eyeCam/name").toString().toStdString().compare(str) == 0)
        return true;
    else
        return false;
}

static bool isSlave(string str)
{
    if (settings.value("fieldCam/name").toString().toStdString().compare(str) == 0)
        return true;
    else
        return false;
}

// This is a workaround to videoman getFrame not respecting the wait parameter.
// As a result, some eye trackers will block while no new image is available whereas others won't.
// Basicaly, we pool the slave camera on a separate thread as not to block the master callback.
static void updateSlave(ImageAcquisition *imageAcquisition)
{
    QElapsedTimer counter;
    Q_ASSERT(counter.isMonotonic());
    double period = 1000/imageAcquisition->slave->format.fps;

    while (imageAcquisition->running) {
        imageAcquisition->slave->buffer.imageData = imageAcquisition->videoManControl.getFrame(imageAcquisition->slave->id, true);
        counter.start();
        Mat tmp;
        if (imageAcquisition->slave->buffer.imageData != NULL) {
            tmp = cvarrToMat(&imageAcquisition->slave->buffer, true);
            flip(tmp, tmp, settings.value("fieldCam/flip").toInt()); // flip before undistorting
            remap(tmp, tmp, imageAcquisition->map1, imageAcquisition->map2, cv::INTER_CUBIC);
            if ( settings.value("fieldCam/outResX").toInt() != tmp.cols ||
                 settings.value("fieldCam/outResY").toInt() != tmp.rows ) {
                resize(
                    tmp,
                    tmp,
                    Size(settings.value("fieldCam/outResX").toInt(), settings.value("fieldCam/outResY").toInt()),
                    INTER_CUBIC
                    );
            }
        }
        imageAcquisition->videoManControl.releaseFrame( imageAcquisition->slave->id );
        imageAcquisition->slaveMutex.lock();
        tmp.copyTo(imageAcquisition->latestSlaveFrame);
        imageAcquisition->slaveMutex.unlock();
        double sleepPeriod = period - counter.elapsed();
        if (sleepPeriod > 0)
            QThread::msleep(sleepPeriod);
    }
}

void ImageAcquisition::onThreadStarted(){
    running = true;
    slaveThread = QtConcurrent::run(updateSlave, this);
}

void ImageAcquisition::onThreadFinished()
{
    running = false;
    slaveThread.waitForFinished();
}

ImageAcquisition::ImageAcquisition(QObject *parent) : QObject(parent),
    videoManControl(VideoManControl::NO_RENDERER)
{
    running = false;
    ready = false;
    master = NULL;
    slave = NULL;

    VMInputIdentification *devList;
    int devCount;

    PerfCounter perfCounter;

    vector<Camera> tmpList;

    // Update the device list
    videoManControl.getAvailableDevices( &devList, devCount );
    qDebug() << "Found "  << devCount << " devices.";

    cameras.clear();
    tmpList.clear();
    for (int i=0; i<devCount; i++) {
        Camera camera;

        qDebug() << devList[i].friendlyName;

        // OpenCV can't enumerate devices and VideoMan can't get the camera format
        // so we have to mix them.
        // IMPORTANT: we assume the OpenCV enumeration is identic to VideoMan's
        VideoCapture cap(i);
        if( ! cap.isOpened() )
        continue;
        int width = cap.get(CAP_PROP_FRAME_WIDTH);
        int height = cap.get(CAP_PROP_FRAME_HEIGHT);
        cap.release();

        camera.name = devList[i].friendlyName;
        camera.format.SetFormat(
            width,
            height,
            0,
            VM_UNKNOWN,
            VM_RGB24 // always assume we have a color image
        );
        camera.format.showDlg = false;
        tmpList.push_back(camera);

        if ( isMaster(devList[i].friendlyName) || isSlave(devList[i].friendlyName)) {
            camera.id = videoManControl.addVideoInput( devList[i], &camera.format );
            videoManControl.getFormat(camera.id, camera.format);

            if (camera.id != -1)
                cameras.push_back(camera);
        }
    }

    videoManControl.freeAvailableDevicesList( &devList, devCount );

    if (cameras.size() < 2 ) {
        QString masterName = settings.value("eyeCam/name").toString();
        if (masterName.isEmpty())
            masterName = "Empty";
        QString tmp(QString("Current master: %1\n").arg(masterName));

        QString slaveName = settings.value("fieldCam/name").toString();
        if (slaveName.isEmpty())
            slaveName = "Empty";
        tmp.append(QString("Current slave: %1\n").arg(slaveName));

        tmp.append("\nThese are the cameras I found:\n\n");
        for (unsigned int i=0; i<tmpList.size(); i++)
            tmp.append(camToStr(tmpList[i])).append("\n");
        tmp.append("\nPossible solutions:\n");
        tmp.append("1) Check your config file.\n");
        tmp.append("2) Make sure no other program is using the cameras.\n");
        tmp.append("3) Turn off the cameras and replug.\n");
        tmp.append("4) Reboot your computer.\n");
        QMessageBox::critical(NULL, "Failed to open cameras.", tmp, QMessageBox::Ok, QMessageBox::NoButton);
        return;
    }

    master = NULL;
    slave = NULL;
    for (unsigned int i=0; i<cameras.size(); i++) {
        Camera* camera = &cameras[i];

        // Let OpenCV describe the image
        IplImage *tmp = cvCreateImage(
                        cvSize( camera->format.width, camera->format.height),
                        camera->format.depth,
                        camera->format.nChannels
                    );
        tmp->origin = 0;
        camera->buffer = *tmp;
        cvReleaseImage(&tmp);

        if ( isMaster(camera->name) )
            master = camera;

        if ( isSlave(camera->name ))
            slave = camera;
    }

    if (slave) {
        qDebug() << "Slave is " << camToStr(*slave);
        setUndistortionMaps( Size( slave->format.width, slave->format.height) );
        latestSlaveFrame = Mat::zeros(slave->format.width, slave->format.height, CV_8UC3);
        putText(latestSlaveFrame, "No valid frame so far...", Point(40,latestSlaveFrame.cols/2), FONT_HERSHEY_SIMPLEX, 1, Scalar(255,255,255), 2);
    }

    if (master) {
        qDebug() << "Master is " << camToStr(*master);

        // support frame callback does not work properly so we test the callback ourselves
        // if( videoManControl.supportFrameCallback(master->id) )
        //videoManControl.setFrameCallback(master->id, &ImageAcquisition::frameCallback, this);
        videoManControl.setFrameCallback(master->id, this->frameCallback, (void*)this);

        qDebug() << "Testing callback...";

        QElapsedTimer timer;
        timer.start();
        while (!ready && !timer.hasExpired(settings.value("eyeCam/callbackMilliSecondTimeout").toInt()) )
            QThread::msleep(100);

        if (ready)
            qDebug() << "Callback works!";
        else {
            qDebug() << "Callback seems broken!";
            QString tmp;
            tmp.append(QString("The master camera callback did not function properly within %1 milliseconds.").arg(settings.value("eyeCam/callbackMilliSecondTimeout").toInt()));
            tmp.append("\nPossible solutions:\n");
            tmp.append("1) Turn off the cameras and replug.\n");
            tmp.append("2) Reboot your computer.\n");
            tmp.append("3) Try a different master.\n");
            tmp.append("4) Increase the callbackMilliSecondTimeout parameter.\n");
            QMessageBox::critical(NULL, "Master callback failed.", tmp, QMessageBox::Ok, QMessageBox::NoButton);
        }
    }
}

ImageAcquisition::~ImageAcquisition()
{
    if (master) {
        videoManControl.setFrameCallback(master->id, NULL, NULL);
        QThread::msleep(100); // Just in case a frame callback was being processed while we are finishing, give it some time to finish
    }
    videoManControl.deleteInputs();
    cameras.clear();
}

void ImageAcquisition::frameCallback(char *pixelBuffer, size_t input, double timestamp, void *data)
{
    ImageAcquisition* imageAcquisition = static_cast<ImageAcquisition*>(data);
    imageAcquisition->frameCallbackInternal(pixelBuffer, input, timestamp);
}

void ImageAcquisition::frameCallbackInternal(char *pixelBuffer, size_t input, double timestamp)
{
    if (!ready)
        recordingStarted = GetTickCount64();
    ready = true;

    if (running && pixelBuffer != NULL) {
        JournalEntry entry(recordingStarted+timestamp*1e3);
        entry.perfCounter.start();

        master->buffer.imageData = pixelBuffer;
237 238 239
        Mat tmp = cvarrToMat(&master->buffer, false);
        if ( settings.value("eyeCam/deinterlace").toBool() )
            naiveDeinterlace(tmp);
Thiago C. Santini's avatar
Thiago C. Santini committed
240
        resize(
241
                tmp,
Thiago C. Santini's avatar
Thiago C. Santini committed
242 243 244 245
                entry.leftEyeFrame,
                Size(settings.value("eyeCam/outResX").toInt(), settings.value("eyeCam/outResY").toInt()),
                INTER_CUBIC
            );
246
        cvtColor(entry.leftEyeFrame, entry.leftEyeFrame, CV_RGB2GRAY); // Assumes the pupil detection uses a grayscale input, may have to be changed later on
Thiago C. Santini's avatar
Thiago C. Santini committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        flip(entry.leftEyeFrame, entry.leftEyeFrame, settings.value("eyeCam/flip").toInt());

        if (slave) {
            // videoMan getFrame function does not respect the wait=false parameter, so we have to update the image on another thread (see updateSlave)
            slaveMutex.lock();
            latestSlaveFrame.copyTo(entry.fieldFrame);
            slaveMutex.unlock();
        }

        entry.incIdx();
        emit imageAcquisitionDone(entry);
    }

    videoManControl.releaseFrame( master->id );
}

void ImageAcquisition::setUndistortionMaps( Size size )
{
    /* Reference: http://docs.opencv.org/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html
         *
         * | Fx,  0, Cx |
         * |  0, Fy, Cy |
         * |  0.  0, 1  |
         *
         * Fx and Fy are the focal lengths (in pixels)
         * ( Cx , Cy ) is the principal point.
         *
         */
    Mat cameraCalibration = (Mat_<float>(3,3) <<
                             settings.value("fieldCam/Fx").toFloat()	,	0.0					,	settings.value("fieldCam/Cx").toFloat()	,
                             0.0				,	settings.value("fieldCam/Fy").toFloat()	,	settings.value("fieldCam/Cy").toFloat()	,
                             0.0				,	0.0					, 	1.0
                             );

    /* Reference: http://docs.opencv.org/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html
         *
         * (k1, k2, p1, p2, k3, k4, k5, k6)
         *
         * k1, k2, k3, k4, k5 and k6 are radial distortion coeficients
         * p1 and p2 are tangential distortion coeficients
         *
         */
    Mat cameraDistortion  = (Mat_<double>(1,8) <<
                             settings.value("fieldCam/k1").toFloat(),
                             settings.value("fieldCam/k2").toFloat(),
                             settings.value("fieldCam/p1").toFloat(),
                             settings.value("fieldCam/p2").toFloat(),
                             settings.value("fieldCam/k3").toFloat(),
                             settings.value("fieldCam/k4").toFloat(),
                             settings.value("fieldCam/k5").toFloat(),
                             settings.value("fieldCam/k6").toFloat()
                             );

    initUndistortRectifyMap(
                            cameraCalibration,
                            cameraDistortion,
                            Mat(),
                            cameraCalibration,
                            size,
                            CV_32FC1,
                            map1,
                            map2
                            );
}

QString ImageAcquisition::camToStr(Camera cam)
{
    QString fps = cam.format.fps == 0 ? "unknown" : QString::number(cam.format.fps);
    return QString("'%1' %2x%3 @ %4 fps").arg(cam.name.c_str()).arg(cam.format.width).arg(cam.format.height).arg(fps);
}

318
void ImageAcquisition::naiveDeinterlace(Mat &in)
Thiago C. Santini's avatar
Thiago C. Santini committed
319
{
320 321
    for (int i=2; i<in.rows-1; i+=2)
        in.row(i).copyTo(in.row(i+1));
Thiago C. Santini's avatar
Thiago C. Santini committed
322
}