CameraWidget.cpp 16 KB
Newer Older
Thiago Santini's avatar
Thiago Santini committed
1 2 3 4 5 6 7
#include "CameraWidget.h"
#include "ui_CameraWidget.h"

using namespace std;
using namespace cv;

CameraWidget::CameraWidget(QString id, ImageProcessor::Type type, QWidget *parent) :
8
	ERWidget(parent),
Thiago Santini's avatar
Thiago Santini committed
9 10 11 12 13 14
    id(id),
    type(type),
    sROI(QPoint(0,0)),
    eROI(QPoint(0,0)),
    settingROI(false),
    lastUpdate(0),
Thiago Santini's avatar
Thiago Santini committed
15
    updateIntervalMs(80),
16 17
	maxAgeMs(300),
	cameraCalibrationSampleRequested(false),
Thiago Santini's avatar
Thiago Santini committed
18 19 20 21 22 23 24 25 26
    ui(new Ui::CameraWidget)
{
    ui->setupUi(this);
    ui->viewFinder->setScaledContents(false);
    ui->viewFinder->setAttribute(Qt::WA_OpaquePaintEvent, true);
    ui->viewFinder->setCursor(Qt::CrossCursor);

    switch (type) {
        case ImageProcessor::Eye:
Thiago Santini's avatar
Thiago Santini committed
27
			ui->viewFinder->setToolTip("You can select a region of interest by clicking and holding the left mouse button.");
Thiago Santini's avatar
Thiago Santini committed
28 29
            break;
        case ImageProcessor::Field:
Thiago Santini's avatar
Thiago Santini committed
30
            ui->viewFinder->setToolTip("After starting the collection you can select points by clicking in this view with the left mouse button.");
Thiago Santini's avatar
Thiago Santini committed
31 32 33 34 35
            break;
        default:
            break;
    }

36 37 38 39 40
    // Early enrollment of stages so they are listed in order :-)
    gPerformanceMonitor.enrol(id, "Frame Grabber");
    gPerformanceMonitor.enrol(id, "Image Processor");
    gPerformanceMonitor.enrol(id, "Data Recorder");

Thiago Santini's avatar
Thiago Santini committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    setWindowTitle(id + " Widget");
    camera = NULL;
    imageProcessor = NULL;

    // Camera
    cameraThread = new QThread();
    cameraThread->setObjectName(id + " Camera");
    cameraThread->start();
    cameraThread->setPriority(QThread::TimeCriticalPriority);
    camera = new Camera(id);
    camera->moveToThread(cameraThread);
    connect(camera, SIGNAL(noCamera(QString)),
            this, SLOT(noCamera(QString)));
    // debugging preview
    //connect(camera, SIGNAL(newFrame(Timestamp, const cv::Mat&)),
56 57 58 59 60 61 62 63
	//    this, SLOT(preview(Timestamp, const cv::Mat&)) );

	cameraCalibration = new CameraCalibration(id);
	connect(cameraCalibration, SIGNAL(requestSample()),
			this, SLOT(requestCameraCalibrationSample()) );
	connect(cameraCalibration, SIGNAL(calibrationFinished(bool)),
			this, SLOT(onCameraCalibrationFinished(bool)) );
	cameraCalibration->load(gCfgDir + "/" + id + "Calibration.xml");
Thiago Santini's avatar
Thiago Santini committed
64 65 66 67 68 69

    // Image Processor
    processorThread = new QThread();
    processorThread->setObjectName(id + " Processor");
    processorThread->start();
    processorThread->setPriority(QThread::TimeCriticalPriority);
70 71 72
	imageProcessor = new ImageProcessor(id, type);
	imageProcessor->cameraCalibration = cameraCalibration;
	imageProcessor->moveToThread(processorThread);
Thiago Santini's avatar
Thiago Santini committed
73 74 75 76 77 78 79 80
    switch (type) {
        case ImageProcessor::Eye:
            imageProcessor->eyeProcessorUI = new EyeImageProcessorUI;
            connect(imageProcessor, SIGNAL(newData(EyeData)),
                    this, SLOT(preview(EyeData)) );
            connect(imageProcessor, SIGNAL(newData(EyeData)),
                    this, SIGNAL(newData(EyeData)) );
            break;
81 82
		case ImageProcessor::Field:
			imageProcessor->fieldProcessorUI = new FieldImageProcessorUI;
Thiago Santini's avatar
Thiago Santini committed
83 84 85 86 87 88 89
            connect(imageProcessor, SIGNAL(newData(FieldData)),
                this, SLOT(preview(FieldData)) );
            connect(imageProcessor, SIGNAL(newData(FieldData)),
                this, SIGNAL(newData(FieldData)) );
            break;
    }
    QMetaObject::invokeMethod(imageProcessor, "create");
90
	connect(camera, SIGNAL(newFrame(Timestamp, const cv::Mat&)),
Thiago Santini's avatar
Thiago Santini committed
91 92 93 94 95 96 97 98 99
        imageProcessor, SIGNAL(process(Timestamp, const cv::Mat&)) );

    // Data Recorder
    recorderThread = new QThread();
    recorderThread->setObjectName(id + " Recorder");
    recorderThread->start();
    recorderThread->setPriority(QThread::NormalPriority);
    recorder = new DataRecorderThread(id, type == ImageProcessor::Eye ? EyeData().header() : FieldData().header());
    recorder->moveToThread(recorderThread);
100
	QMetaObject::invokeMethod(recorder, "create");
Thiago Santini's avatar
Thiago Santini committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    // GUI
    optionsGroup = new QActionGroup(this);
    connect(optionsGroup, SIGNAL(triggered(QAction*)),
            this, SLOT(options(QAction*)));

    optionAction = new QAction("Camera", optionsGroup);
    optionAction->setData(QVariant::fromValue(optionAction->text()));
    optionAction->setCheckable(false);
    ui->menuOptions->addAction(optionAction);

    optionAction = new QAction("Image Processor", optionsGroup);
    optionAction->setData(QVariant::fromValue(optionAction->text()));
    optionAction->setCheckable(false);
    ui->menuOptions->addAction(optionAction);

    optionAction = new QAction("Calibrate Camera", optionsGroup);
    optionAction->setData(QVariant::fromValue(optionAction->text()));
    optionAction->setCheckable(false);
    ui->menuOptions->addAction(optionAction);

    connect(this, SIGNAL(newROI(QPointF,QPointF)),
            imageProcessor, SIGNAL(newROI(QPointF,QPointF)) );

Thiago Santini's avatar
Thiago Santini committed
125
	// Initial roi
Thiago Santini's avatar
Thiago Santini committed
126
	setROI( QPointF(0.15, 0.1), QPointF(0.85, 0.9) );
Thiago Santini's avatar
Thiago Santini committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    QMetaObject::invokeMethod(camera, "loadCfg");
}

CameraWidget::~CameraWidget()
{
    delete ui;

    if (camera) {
        camera->deleteLater();
        camera = NULL;
    }

    if (imageProcessor) {
        imageProcessor->deleteLater();
        imageProcessor = NULL;
    }

    if (recorder) {
        recorder->deleteLater();
        recorder = NULL;
147 148 149 150 151 152
	}

	if (cameraCalibration) {
		cameraCalibration->deleteLater();
		cameraCalibration = NULL;
	}
Thiago Santini's avatar
Thiago Santini committed
153 154 155 156 157 158 159 160

    cameraThread->quit();
    cameraThread->wait();

    processorThread->quit();
    processorThread->wait();

    recorderThread->quit();
161
	recorderThread->wait();
Thiago Santini's avatar
Thiago Santini committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
}

void CameraWidget::preview(Timestamp t, const cv::Mat &frame)
{
    updateFrameRate(t);
    if (!shouldUpdate(t))
        return;
    if (!isDataRecent(t))
        return;
    QImage scaled = previewImage(frame);

    QPainter painter(&scaled);
    ui->viewFinder->setPixmap(QPixmap::fromImage(scaled));
}

void CameraWidget::preview(EyeData data)
{
    if (data.input.empty()) // if there's no eye image, don't update
        return;

    updateFrameRate(data.timestamp);
    if (!shouldUpdate(data.timestamp))
        return;
    if (!isDataRecent(data.timestamp))
Thiago Santini's avatar
Thiago Santini committed
186 187 188
		return;

	updateWidgetSize(data.input.cols, data.input.rows);
Thiago Santini's avatar
Thiago Santini committed
189

Thiago Santini's avatar
Thiago Santini committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
	QImage scaled = previewImage(data.input);
	QRectF userROI = {
			QPointF( ui->viewFinder->width()*sROI.x(), ui->viewFinder->height()*sROI.y() ),
			QPointF( ui->viewFinder->width()*(eROI.x()), ui->viewFinder->height()*(eROI.y()) )
		};
	QRectF coarseROI = {
		QPointF(
			ui->viewFinder->width() * data.coarseROI.tl().x / (float) data.input.cols,
			ui->viewFinder->height() * data.coarseROI.tl().y / (float) data.input.rows
			),
		QPointF(
			ui->viewFinder->width() * data.coarseROI.br().x / (float) data.input.cols,
			ui->viewFinder->height() * data.coarseROI.br().y / (float) data.input.rows
			)
		};

	eyeOverlay.drawOverlay(data, userROI, coarseROI, scaled);
207 208 209
	ui->viewFinder->setPixmap(QPixmap::fromImage(scaled));

	sendCameraCalibrationSample(data.input);
Thiago Santini's avatar
Thiago Santini committed
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
}

void CameraWidget::preview(FieldData data)
{
    // We only update the camera frame rate here. Viewfinder is updated
    // based on the signal from the gaze estimation stage
    updateFrameRate(data.timestamp);
}
void CameraWidget::preview(const DataTuple &data)
{
    if (data.field.input.empty()) // If there's no field image, don't update
        return;

    if (!shouldUpdate(data.timestamp))
        return;
    if (!isDataRecent(data.field.timestamp))
        return;

Thiago Santini's avatar
Thiago Santini committed
228 229 230 231 232
	Mat input;
	if (data.showGazeEstimationVisualization && !data.gazeEstimationVisualization.empty())
		input = data.gazeEstimationVisualization;
	else
		input = data.field.input;
Thiago Santini's avatar
Thiago Santini committed
233 234

	updateWidgetSize(input.cols, input.rows);
Thiago Santini's avatar
Thiago Santini committed
235

Thiago Santini's avatar
Thiago Santini committed
236 237
	QImage scaled = previewImage(input);
	fieldOverlay.drawOverlay(data, scaled);;
238 239 240
	ui->viewFinder->setPixmap(QPixmap::fromImage(scaled));

	sendCameraCalibrationSample(input);
Thiago Santini's avatar
Thiago Santini committed
241 242 243 244
}

void CameraWidget::updateFrameRate(Timestamp t)
{
Thiago Santini's avatar
Thiago Santini committed
245 246 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
	// Simpler version since the status bar update showed some overhead
	// during tests with OpenGL
	if (tq.size() == 0) {
		ui->statusbar->showMessage(
			QString("%1 @ N/A FPS").arg(
					camera->currentCameraInfo.description()
				)
			);
		tq.push_back(t);
		lastFrameRateUpdate = t;
		return;
	}

	tq.push_back(t);
	if (tq.size() > 30) {
		tq.pop_front();
		if (tq.back() - lastFrameRateUpdate > 100) { // update every 100 ms
			double fps = (tq.size()-1) / (1.0e-3*( tq.back() - tq.front() ) );
			lastFrameRateUpdate = tq.back();
			ui->statusbar->showMessage(
				QString("%1 @ %2 FPS").arg(
					camera->currentCameraInfo.description()).arg(
						fps, 0, 'f', 2
					)
				);
		}
	}

Thiago Santini's avatar
Thiago Santini committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
}

void CameraWidget::noCamera(QString msg)
{
    ui->statusbar->showMessage(msg, 0);
    QImage blank(ui->viewFinder->size(), QImage::Format_RGB888);
    blank.fill(Qt::black);
    ui->viewFinder->setPixmap(QPixmap::fromImage(blank));
}

void CameraWidget::options(QAction* action)
{
    QString option = action->data().toString().toLower();

    if (option == "camera") {
        if (camera) {
            camera->ui->move(this->pos());
            QMetaObject::invokeMethod(camera, "showOptions", Qt::QueuedConnection);
        }
    }
    if (option == "image processor")
        if (imageProcessor)
            QMetaObject::invokeMethod(imageProcessor, "showOptions", Qt::QueuedConnection, Q_ARG(QPoint, this->pos()));

297 298 299
	if (option == "calibrate camera")
		if (cameraCalibration)
			QMetaObject::invokeMethod(cameraCalibration, "showOptions", Qt::QueuedConnection, Q_ARG(QPoint, this->pos()));
Thiago Santini's avatar
Thiago Santini committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313
}

void CameraWidget::startRecording()
{
    ui->menubar->setEnabled(false);
    QMetaObject::invokeMethod(recorder, "startRecording", Q_ARG(double, camera->fps));
    connect(imageProcessor, SIGNAL(newData(EyeData)),
            recorder, SIGNAL(newData(EyeData)) );
    connect(imageProcessor, SIGNAL(newData(FieldData)),
            recorder, SIGNAL(newData(FieldData)) );
}

void CameraWidget::stopRecording()
{
314 315 316 317 318
	disconnect(imageProcessor, SIGNAL(newData(EyeData)),
			recorder, SIGNAL(newData(EyeData)) );
	disconnect(imageProcessor, SIGNAL(newData(FieldData)),
			recorder, SIGNAL(newData(FieldData)) );
	QMetaObject::invokeMethod(recorder, "stopRecording", Qt::QueuedConnection);
Thiago Santini's avatar
Thiago Santini committed
319 320 321 322 323 324
    ui->menubar->setEnabled(true);
}

void CameraWidget::mousePressEvent(QMouseEvent *event)
{
    if (ui->viewFinder->underMouse()) {
Thiago Santini's avatar
Thiago Santini committed
325
		if (event->button() == Qt::LeftButton && type == ImageProcessor::Field)
Thiago Santini's avatar
Thiago Santini committed
326 327
            emit newClick( gTimer.elapsed(), ui->viewFinder->mapFromGlobal(this->mapToGlobal(event->pos())), ui->viewFinder->size());

Thiago Santini's avatar
Thiago Santini committed
328
		if (event->button() == Qt::LeftButton && type == ImageProcessor::Eye) {
Thiago Santini's avatar
Thiago Santini committed
329 330 331 332
            sROI = ui->viewFinder->mapFrom(this, event->pos());
            validatePoint(sROI);
            sROI.setX( sROI.x() / ui->viewFinder->width());
            sROI.setY( sROI.y() / ui->viewFinder->height());
Thiago Santini's avatar
Thiago Santini committed
333
			eROI = sROI;
Thiago Santini's avatar
Thiago Santini committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
            settingROI = true;
        }
    }
}

void CameraWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (ui->viewFinder->underMouse()) {
        if (settingROI) {
            eROI = ui->viewFinder->mapFrom(this, event->pos());
            validatePoint(eROI);
            eROI.setX( eROI.x() / ui->viewFinder->width());
            eROI.setY( eROI.y() / ui->viewFinder->height());
        }
    }
}

void CameraWidget::mouseReleaseEvent(QMouseEvent *event)
{
Thiago Santini's avatar
Thiago Santini committed
353
	if (event->button() == Qt::LeftButton && type == ImageProcessor::Eye) {
354 355 356 357 358 359 360 361
        eROI = ui->viewFinder->mapFrom(this, event->pos());
        validatePoint(eROI);
        eROI.setX( eROI.x() / ui->viewFinder->width());
        eROI.setY( eROI.y() / ui->viewFinder->height());
        settingROI = false;
        if ( abs(sROI.x() - eROI.x()) < 0.1 || abs(sROI.y() - eROI.y()) < 0.1 ) {
            sROI = QPointF();
            eROI = QPointF();
Thiago Santini's avatar
Thiago Santini committed
362
        }
Thiago Santini's avatar
Thiago Santini committed
363
		setROI(sROI, eROI);
Thiago Santini's avatar
Thiago Santini committed
364 365 366 367 368
    }
}

void CameraWidget::validatePoint(QPointF &point)
{
369 370 371 372
    if (point.x() < 1)
        point.setX(1);
    if (point.y() < 1)
        point.setY(1);
Thiago Santini's avatar
Thiago Santini committed
373
    if (point.x() > ui->viewFinder->width())
374
        point.setX(ui->viewFinder->width()-1);
Thiago Santini's avatar
Thiago Santini committed
375
    if (point.y() > ui->viewFinder->height())
376
        point.setY(ui->viewFinder->height()-1);
Thiago Santini's avatar
Thiago Santini committed
377 378 379 380 381 382 383
}

bool CameraWidget::shouldUpdate(Timestamp t)
{
    if (!this->isVisible())
        return false;

Thiago Santini's avatar
Thiago Santini committed
384 385 386 387 388 389 390 391 392 393 394 395
	/* TODO: Right now, we don't update every frame to save resources.
	 * Make this parametrizable or move to faster drawing methods.
	 *
	 * Notes: I've tried some initial tests to move to OpenGL, which were
	 * unsuccessful. This includes using QPainter with QOpenGLWidgets, native
	 * OpenGL directives (using QUADs, TRIANGLES, and an FBO).
	 * In all cases I saw a similar behavior: scaling/drawing is faster, but I
	 * get CPU hogs from other places -- e.g., additional calls to nvogl,
	 * NtGdiDdDDIEscape (whatever that is!), and calls to wglMakeCurrent
	 * (which seem to be rather expensive!).
	 * If anyone who actually knows OpenGL wanna try, be my guest :-)
	 */
Thiago Santini's avatar
Thiago Santini committed
396 397 398 399 400 401 402 403 404 405 406 407 408
    if (t - lastUpdate > updateIntervalMs) {
        lastUpdate = t;
        return true;
    }

    return false;
}

bool CameraWidget::isDataRecent(Timestamp t)
{
    Timestamp cur = gTimer.elapsed();
    if (cur - t < maxAgeMs) // TODO: make this based on estimated FPS?
        return true;
409 410
    if (cur - lastUpdate > maxAgeMs) { // not recent, but we haven't update in a while
        lastUpdate = cur;
Thiago Santini's avatar
Thiago Santini committed
411
        return true;
412
    }
Thiago Santini's avatar
Thiago Santini committed
413 414 415 416 417 418 419 420 421
    return false;
}

QImage CameraWidget::previewImage(const cv::Mat &frame)
{
    Size previewSize(ui->viewFinder->width(), ui->viewFinder->height());

    switch (frame.channels()) {
        case 1:
Thiago Santini's avatar
Thiago Santini committed
422 423 424
			cvtColor(frame, rgb, CV_GRAY2RGB);
			cv::resize(rgb, resized, previewSize, cv::INTER_NEAREST);
			break;
Thiago Santini's avatar
Thiago Santini committed
425
        case 3:
Thiago Santini's avatar
Thiago Santini committed
426 427
			cvtColor(frame, rgb, CV_BGR2RGB);
			cv::resize(rgb, resized, previewSize, cv::INTER_NEAREST);
Thiago Santini's avatar
Thiago Santini committed
428 429
            break;
        default:
Thiago Santini's avatar
Thiago Santini committed
430
			resized = cv::Mat::zeros(previewSize, CV_8UC3);
Thiago Santini's avatar
Thiago Santini committed
431
            break;
Thiago Santini's avatar
Thiago Santini committed
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
	}

	/* TODO: according to http://doc.qt.io/qt-5/qpainter.html
	 *
	 * "Raster - This backend implements all rendering in pure software and is
	 * always used to render into QImages. For optimal performance only use the
	 * format types QImage::Format_ARGB32_Premultiplied, QImage::Format_RGB32 or
	 * QImage::Format_RGB16. Any other format, including QImage::Format_ARGB32,
	 * has significantly worse performance. This engine is used by default for
	 * QWidget and QPixmap."
	 *
	 * However, I've found that resizing with OpenCV using only three bytes
	 * results in faster and less cpu-intensive code.
	 * This is relative to ARGB32_Premultiplied (which should be the fastest
	 * option with QImages, according to http://doc.qt.io/qt-5/qimage.html
	 *
	 */
Thiago Santini's avatar
Thiago Santini committed
449
	return QImage(resized.data, resized.cols, resized.rows, (int) resized.step, QImage::Format_RGB888);
Thiago Santini's avatar
Thiago Santini committed
450 451
}

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
void CameraWidget::sendCameraCalibrationSample(const cv::Mat &frame)
{
	if (!cameraCalibrationSampleRequested || !cameraCalibration)
		return;
	cameraCalibrationSampleRequested = false;
	QMetaObject::invokeMethod(cameraCalibration, "newSample", Qt::QueuedConnection, Q_ARG(cv::Mat, frame));
	emit sendCameraCalibrationSample(frame);
}

void CameraWidget::onCameraCalibrationFinished(bool success)
{
	if (!success)
		return;
	// TODO: at some point we might consider storing this with a unique camera ID instead of this generic one
	QString fileName = gCfgDir + "/" + id + "Calibration.xml";
467 468
	// Do the store here with a direct call to guarantee it will be done before the updateConfig
	QMetaObject::invokeMethod(cameraCalibration, "store", Qt::DirectConnection, Q_ARG(QString, fileName));
469
	QMetaObject::invokeMethod(imageProcessor,  "updateConfig", Qt::QueuedConnection);
470 471
}

Thiago Santini's avatar
Thiago Santini committed
472 473
void CameraWidget::updateWidgetSize(const int &width, const int &height)
{
Thiago Santini's avatar
Thiago Santini committed
474 475 476 477 478 479
	if ( this->type == ImageProcessor::Eye)
		this->setMaximumSize(320, 240);
	if ( this->type == ImageProcessor::Field)
		this->setMaximumSize(640, 360);
	return;

Thiago Santini's avatar
Thiago Santini committed
480 481 482 483 484 485
	// Logic to limit the size of the camera widgets
	QSize newFrameSize = { width, height };
	if (frameSize == newFrameSize)
		return;

	frameSize = newFrameSize;
486
	QSize minMaxSize = { 640 , 480 };
Thiago Santini's avatar
Thiago Santini committed
487
	QSize maxSize = { 960 , 540 };
488 489 490 491 492 493
	if (frameSize.width() < maxSize.width() && frameSize.height() < maxSize.height() ) {
		if (frameSize.width() < minMaxSize.width() && frameSize.height() < minMaxSize.height()) {
			float ratio = minMaxSize.width() / (float) frameSize.width();
			frameSize.setWidth(minMaxSize.width());
			frameSize.setHeight(ratio * minMaxSize.height());
		}
Thiago Santini's avatar
Thiago Santini committed
494
		this->setMaximumSize( frameSize );
495
	} else
Thiago Santini's avatar
Thiago Santini committed
496 497
		this->setMaximumSize( maxSize );
}