1 //IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
3 // By downloading, copying, installing or using the software you agree to this license.
4 // If you do not agree to this license, do not download, install,
5 // copy or use the software.
9 // For Open Source Computer Vision Library
11 //Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
12 //Copyright (C) 2008-2010, Willow Garage Inc., all rights reserved.
13 //Third party copyrights are property of their respective owners.
15 //Redistribution and use in source and binary forms, with or without modification,
16 //are permitted provided that the following conditions are met:
18 // * Redistribution's of source code must retain the above copyright notice,
19 // this list of conditions and the following disclaimer.
21 // * Redistribution's in binary form must reproduce the above copyright notice,
22 // this list of conditions and the following disclaimer in the documentation
23 // and/or other materials provided with the distribution.
25 // * The name of the copyright holders may not be used to endorse or promote products
26 // derived from this software without specific prior written permission.
28 //This software is provided by the copyright holders and contributors "as is" and
29 //any express or implied warranties, including, but not limited to, the implied
30 //warranties of merchantability and fitness for a particular purpose are disclaimed.
31 //In no event shall the Intel Corporation or contributors be liable for any direct,
32 //indirect, incidental, special, exemplary, or consequential damages
33 //(including, but not limited to, procurement of substitute goods or services;
34 //loss of use, data, or profits; or business interruption) however caused
35 //and on any theory of liability, whether in contract, strict liability,
36 //or tort (including negligence or otherwise) arising in any way out of
37 //the use of this software, even if advised of the possibility of such damage.
39 //--------------------Google Code 2010 -- Yannick Verdie--------------------//
41 #include "precomp.hpp"
47 #include <window_QT.h>
64 //Static and global first
65 static GuiReceiver *guiMainThread = NULL;
66 static int parameterSystemC = 1;
67 static char* parameterSystemV[] = {(char*)""};
68 static bool multiThreads = false;
69 static int last_key = -1;
70 QWaitCondition key_pressed;
72 static const unsigned int threshold_zoom_img_region = 30;
73 //the minimum zoom value to start displaying the values in the grid
74 //that is also the number of pixel per grid
76 static CvWinProperties* global_control_panel = NULL;
77 //end static and global
80 Qt::ConnectionType autoBlockingConnection();
82 // Implementation - this allows us to do blocking whilst automatically selecting the right
83 // behaviour for in-thread and out-of-thread launches of cv windows. Qt strangely doesn't
84 // cater for this, but does for strictly queued connections.
85 Qt::ConnectionType autoBlockingConnection() {
86 return (QThread::currentThread() != QApplication::instance()->thread())
87 ? Qt::BlockingQueuedConnection
88 : Qt::DirectConnection;
91 CV_IMPL CvFont cvFontQt(const char* nameFont, int pointSize,CvScalar color,int weight,int style, int spacing)
95 //CvScalar color <- only Qt (blue_component, green_component, red\_component[, alpha_component])
96 int font_face;//<- style in Qt
100 float hscale, vscale;
102 int thickness;//<- weight in Qt
103 float dx;//spacing letter in Qt (0 default) in pixel
104 int line_type;//<- pointSize in Qt
106 CvFont f = {nameFont,color,style,NULL,NULL,NULL,0,0,0,weight,spacing,pointSize};
111 CV_IMPL void cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont* font)
114 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
116 QMetaObject::invokeMethod(guiMainThread,
118 autoBlockingConnection(),
119 Q_ARG(void*, (void*) img),
120 Q_ARG(QString,QString(text)),
121 Q_ARG(QPoint, QPoint(org.x,org.y)),
122 Q_ARG(void*,(void*) font));
126 double cvGetRatioWindow_QT(const char* name)
129 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
132 QMetaObject::invokeMethod(guiMainThread,
134 autoBlockingConnection(),
135 Q_RETURN_ARG(double, result),
136 Q_ARG(QString, QString(name)));
142 void cvSetRatioWindow_QT(const char* name,double prop_value)
146 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
148 QMetaObject::invokeMethod(guiMainThread,
150 autoBlockingConnection(),
151 Q_ARG(QString, QString(name)),
152 Q_ARG(double, prop_value));
156 double cvGetPropWindow_QT(const char* name)
159 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
162 QMetaObject::invokeMethod(guiMainThread,
164 autoBlockingConnection(),
165 Q_RETURN_ARG(double, result),
166 Q_ARG(QString, QString(name)));
172 void cvSetPropWindow_QT(const char* name,double prop_value)
175 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
177 QMetaObject::invokeMethod(guiMainThread,
179 autoBlockingConnection(),
180 Q_ARG(QString, QString(name)),
181 Q_ARG(double, prop_value));
184 void cv::setWindowTitle(const String& winname, const String& title)
187 CV_Error(Error::StsNullPtr, "NULL guiReceiver (please create a window)");
189 QMetaObject::invokeMethod(guiMainThread,
191 autoBlockingConnection(),
192 Q_ARG(QString, QString(winname.c_str())),
193 Q_ARG(QString, QString(title.c_str())));
197 void cvSetModeWindow_QT(const char* name, double prop_value)
200 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
202 QMetaObject::invokeMethod(guiMainThread,
204 autoBlockingConnection(),
205 Q_ARG(QString, QString(name)),
206 Q_ARG(double, prop_value));
210 double cvGetModeWindow_QT(const char* name)
213 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
217 QMetaObject::invokeMethod(guiMainThread,
219 autoBlockingConnection(),
220 Q_RETURN_ARG(double, result),
221 Q_ARG(QString, QString(name)));
227 CV_IMPL void cvDisplayOverlay(const char* name, const char* text, int delayms)
230 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
232 QMetaObject::invokeMethod(guiMainThread,
234 autoBlockingConnection(),
235 Q_ARG(QString, QString(name)),
236 Q_ARG(QString, QString(text)),
237 Q_ARG(int, delayms));
241 CV_IMPL void cvSaveWindowParameters(const char* name)
244 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
246 QMetaObject::invokeMethod(guiMainThread,
247 "saveWindowParameters",
248 autoBlockingConnection(),
249 Q_ARG(QString, QString(name)));
253 CV_IMPL void cvLoadWindowParameters(const char* name)
256 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
258 QMetaObject::invokeMethod(guiMainThread,
259 "loadWindowParameters",
260 autoBlockingConnection(),
261 Q_ARG(QString, QString(name)));
265 CV_IMPL void cvDisplayStatusBar(const char* name, const char* text, int delayms)
268 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
270 QMetaObject::invokeMethod(guiMainThread,
272 autoBlockingConnection(),
273 Q_ARG(QString, QString(name)),
274 Q_ARG(QString, QString(text)),
275 Q_ARG(int, delayms));
279 CV_IMPL int cvWaitKey(int delay)
286 unsigned long delayms = delay <= 0 ? ULONG_MAX : delay; //in milliseconds
291 if (key_pressed.wait(&mutexKey, delayms)) //false if timeout
300 //cannot use wait here because events will not be distributed before processEvents (the main eventLoop is broken)
301 //so I create a Thread for the QTimer
304 guiMainThread->timer->start(delay);
308 while (!guiMainThread->bTimeOut)
310 qApp->processEvents(QEventLoop::AllEvents);
312 if (!guiMainThread)//when all the windows are deleted
320 guiMainThread->timer->stop();
321 //printf("keypressed\n");
332 * //will not work, I broke the event loop !!!!
334 QWaitCondition waitCondition;
335 waitCondition.wait(&dummy, 2);
338 //to decrease CPU usage
339 //sleep 1 millisecond
340 #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64
348 guiMainThread->bTimeOut = false;
355 //This function is experimental and some functions (such as cvSet/getWindowProperty will not work)
356 //We recommend not using this function for now
357 CV_IMPL int cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[])
360 QFuture<int> future = QtConcurrent::run(pt2Func, argc, argv);
361 return guiMainThread->start();
365 CV_IMPL void cvStopLoop()
371 static CvWindow* icvFindWindowByName(QString name)
373 CvWindow* window = 0;
375 //This is not a very clean way to do the stuff. Indeed, QAction automatically generate toolTil (QLabel)
376 //that can be grabbed here and crash the code at 'w->param_name==name'.
377 foreach (QWidget* widget, QApplication::topLevelWidgets())
379 if (widget->isWindow() && !widget->parentWidget())//is a window without parent
381 CvWinModel* temp = (CvWinModel*) widget;
383 if (temp->type == type_CvWindow)
385 CvWindow* w = (CvWindow*) temp;
386 if (w->objectName() == name)
399 static CvBar* icvFindBarByName(QBoxLayout* layout, QString name_bar, typeBar type)
404 int stop_index = layout->layout()->count();
406 for (int i = 0; i < stop_index; ++i)
408 CvBar* t = (CvBar*) layout->layout()->itemAt(i);
410 if (t->type == type && t->name_bar == name_bar)
418 static CvTrackbar* icvFindTrackBarByName(const char* name_trackbar, const char* name_window, QBoxLayout* layout = NULL)
420 QString nameQt(name_trackbar);
421 if ((!name_window || !name_window[0]) && global_control_panel) //window name is null and we have a control panel
422 layout = global_control_panel->myLayout;
426 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(name_window));
429 CV_Error(CV_StsNullPtr, "NULL window handler");
431 if (w->param_gui_mode == CV_GUI_NORMAL)
432 return (CvTrackbar*) icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
434 if (w->param_gui_mode == CV_GUI_EXPANDED)
436 CvBar* result = icvFindBarByName(w->myBarLayout, nameQt, type_CvTrackbar);
439 return (CvTrackbar*) result;
441 return (CvTrackbar*) icvFindBarByName(global_control_panel->myLayout, nameQt, type_CvTrackbar);
448 //layout was specified
449 return (CvTrackbar*) icvFindBarByName(layout, nameQt, type_CvTrackbar);
454 static CvButtonbar* icvFindButtonBarByName(const char* button_name, QBoxLayout* layout)
456 QString nameQt(button_name);
457 return (CvButtonbar*) icvFindBarByName(layout, nameQt, type_CvButtonbar);
461 static int icvInitSystem(int* c, char** v)
463 //"For any GUI application using Qt, there is precisely one QApplication object"
464 if (!QApplication::instance())
466 new QApplication(*c, v);
467 setlocale(LC_NUMERIC,"C");
469 qDebug() << "init done";
471 #ifdef HAVE_QT_OPENGL
472 qDebug() << "opengl support available";
480 CV_IMPL int cvInitSystem(int, char**)
482 icvInitSystem(¶meterSystemC, parameterSystemV);
487 CV_IMPL int cvNamedWindow(const char* name, int flags)
490 guiMainThread = new GuiReceiver;
491 if (QThread::currentThread() != QApplication::instance()->thread()) {
493 QMetaObject::invokeMethod(guiMainThread,
495 Qt::BlockingQueuedConnection, // block so that we can do useful stuff once we confirm it is created
496 Q_ARG(QString, QString(name)),
499 guiMainThread->createWindow(QString(name), flags);
502 return 1; //Dummy value - probably should return the result of the invocation.
506 CV_IMPL void cvDestroyWindow(const char* name)
509 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
511 QMetaObject::invokeMethod(guiMainThread,
513 Qt::AutoConnection, // if another thread is controlling, let it handle it without blocking ourselves here
514 Q_ARG(QString, QString(name)));
518 CV_IMPL void cvDestroyAllWindows()
522 QMetaObject::invokeMethod(guiMainThread,
524 Qt::AutoConnection // if another thread is controlling, let it handle it without blocking ourselves here
529 CV_IMPL void* cvGetWindowHandle(const char* name)
532 CV_Error( CV_StsNullPtr, "NULL name string" );
534 return (void*) icvFindWindowByName(QLatin1String(name));
538 CV_IMPL const char* cvGetWindowName(void* window_handle)
541 CV_Error( CV_StsNullPtr, "NULL window handler" );
543 return ((CvWindow*)window_handle)->objectName().toLatin1().data();
547 CV_IMPL void cvMoveWindow(const char* name, int x, int y)
550 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
551 QMetaObject::invokeMethod(guiMainThread,
553 autoBlockingConnection(),
554 Q_ARG(QString, QString(name)),
559 CV_IMPL void cvResizeWindow(const char* name, int width, int height)
562 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
563 QMetaObject::invokeMethod(guiMainThread,
565 autoBlockingConnection(),
566 Q_ARG(QString, QString(name)),
572 CV_IMPL int cvCreateTrackbar2(const char* name_bar, const char* window_name, int* val, int count, CvTrackbarCallback2 on_notify, void* userdata)
575 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
577 QMetaObject::invokeMethod(guiMainThread,
579 autoBlockingConnection(),
580 Q_ARG(QString, QString(name_bar)),
581 Q_ARG(QString, QString(window_name)),
582 Q_ARG(void*, (void*)val),
584 Q_ARG(void*, (void*)on_notify),
585 Q_ARG(void*, (void*)userdata));
587 return 1; //dummy value
591 CV_IMPL int cvStartWindowThread()
597 CV_IMPL int cvCreateTrackbar(const char* name_bar, const char* window_name, int* value, int count, CvTrackbarCallback on_change)
600 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
602 QMetaObject::invokeMethod(guiMainThread,
604 autoBlockingConnection(),
605 Q_ARG(QString, QString(name_bar)),
606 Q_ARG(QString, QString(window_name)),
607 Q_ARG(void*, (void*)value),
609 Q_ARG(void*, (void*)on_change));
611 return 1; //dummy value
615 CV_IMPL int cvCreateButton(const char* button_name, CvButtonCallback on_change, void* userdata, int button_type, int initial_button_state)
618 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
620 if (initial_button_state < 0 || initial_button_state > 1)
623 QMetaObject::invokeMethod(guiMainThread,
625 autoBlockingConnection(),
626 Q_ARG(QString, QString(button_name)),
627 Q_ARG(int, button_type),
628 Q_ARG(int, initial_button_state),
629 Q_ARG(void*, (void*)on_change),
630 Q_ARG(void*, userdata));
632 return 1;//dummy value
636 CV_IMPL int cvGetTrackbarPos(const char* name_bar, const char* window_name)
640 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
643 result = t->slider->value();
649 CV_IMPL void cvSetTrackbarPos(const char* name_bar, const char* window_name, int pos)
651 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
654 t->slider->setValue(pos);
658 CV_IMPL void cvSetTrackbarMax(const char* name_bar, const char* window_name, int maxval)
662 QPointer<CvTrackbar> t = icvFindTrackBarByName(name_bar, window_name);
665 t->slider->setMaximum(maxval);
671 /* assign callback for mouse events */
672 CV_IMPL void cvSetMouseCallback(const char* window_name, CvMouseCallback on_mouse, void* param)
674 QPointer<CvWindow> w = icvFindWindowByName(QLatin1String(window_name));
677 CV_Error(CV_StsNullPtr, "NULL window handler");
679 w->setMouseCallBack(on_mouse, param);
684 CV_IMPL void cvShowImage(const char* name, const CvArr* arr)
687 guiMainThread = new GuiReceiver;
688 if (QThread::currentThread() != QApplication::instance()->thread()) {
690 QMetaObject::invokeMethod(guiMainThread,
692 autoBlockingConnection(),
693 Q_ARG(QString, QString(name)),
694 Q_ARG(void*, (void*)arr)
697 guiMainThread->showImage(QString(name), (void*)arr);
702 #ifdef HAVE_QT_OPENGL
704 CV_IMPL void cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata)
707 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
709 QMetaObject::invokeMethod(guiMainThread,
710 "setOpenGlDrawCallback",
711 autoBlockingConnection(),
712 Q_ARG(QString, QString(window_name)),
713 Q_ARG(void*, (void*)callback),
714 Q_ARG(void*, userdata));
718 CV_IMPL void cvSetOpenGlContext(const char* window_name)
721 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
723 QMetaObject::invokeMethod(guiMainThread,
725 autoBlockingConnection(),
726 Q_ARG(QString, QString(window_name)));
730 CV_IMPL void cvUpdateWindow(const char* window_name)
733 CV_Error( CV_StsNullPtr, "NULL guiReceiver (please create a window)" );
735 QMetaObject::invokeMethod(guiMainThread,
737 autoBlockingConnection(),
738 Q_ARG(QString, QString(window_name)));
744 double cvGetOpenGlProp_QT(const char* name)
750 QMetaObject::invokeMethod(guiMainThread,
752 autoBlockingConnection(),
753 Q_RETURN_ARG(double, result),
754 Q_ARG(QString, QString(name)));
761 //////////////////////////////////////////////////////
765 GuiReceiver::GuiReceiver() : bTimeOut(false), nb_windows(0)
767 doesExternalQAppExist = (QApplication::instance() != 0);
768 icvInitSystem(¶meterSystemC, parameterSystemV);
770 timer = new QTimer(this);
771 QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
772 timer->setSingleShot(true);
773 if ( doesExternalQAppExist ) {
774 moveToThread(QApplication::instance()->thread());
779 void GuiReceiver::isLastWindow()
781 if (--nb_windows <= 0)
783 delete guiMainThread;//delete global_control_panel too
784 guiMainThread = NULL;
786 if (!doesExternalQAppExist)
794 GuiReceiver::~GuiReceiver()
796 if (global_control_panel)
798 delete global_control_panel;
799 global_control_panel = NULL;
804 void GuiReceiver::putText(void* arr, QString text, QPoint org, void* arg2)
809 mat = cvGetMat(arr, &stub);
811 int nbChannelOriginImage = cvGetElemType(mat);
812 if (nbChannelOriginImage != CV_8UC3) return; //for now, font works only with 8UC3
814 QImage qimg(mat->data.ptr, mat->cols, mat->rows, mat->step, QImage::Format_RGB888);
816 CvFont* font = (CvFont*)arg2;
821 QFont f(font->nameFont, font->line_type/*PointSize*/, font->thickness/*weight*/);
822 f.setStyle((QFont::Style) font->font_face/*style*/);
823 f.setLetterSpacing(QFont::AbsoluteSpacing, font->dx/*spacing*/);
824 //cvScalar(blue_component, green_component, red_component[, alpha_component])
825 //Qt map non-transparent to 0xFF and transparent to 0
826 //OpenCV scalar is the reverse, so 255-font->color.val[3]
827 qp.setPen(QColor(font->color.val[2], font->color.val[1], font->color.val[0], 255 - font->color.val[3]));
830 qp.drawText(org, text);
835 void GuiReceiver::saveWindowParameters(QString name)
837 QPointer<CvWindow> w = icvFindWindowByName(name);
844 void GuiReceiver::loadWindowParameters(QString name)
846 QPointer<CvWindow> w = icvFindWindowByName(name);
853 double GuiReceiver::getRatioWindow(QString name)
855 QPointer<CvWindow> w = icvFindWindowByName(name);
860 return w->getRatio();
864 void GuiReceiver::setRatioWindow(QString name, double arg2)
866 QPointer<CvWindow> w = icvFindWindowByName( name.toLatin1().data() );
871 int flags = (int) arg2;
877 double GuiReceiver::getPropWindow(QString name)
879 QPointer<CvWindow> w = icvFindWindowByName(name);
884 return (double) w->getPropWindow();
888 void GuiReceiver::setPropWindow(QString name, double arg2)
890 QPointer<CvWindow> w = icvFindWindowByName(name);
895 int flags = (int) arg2;
897 w->setPropWindow(flags);
900 void GuiReceiver::setWindowTitle(QString name, QString title)
902 QPointer<CvWindow> w = icvFindWindowByName(name);
906 cvNamedWindow(name.toLatin1().data());
907 w = icvFindWindowByName(name);
913 w->setWindowTitle(title);
917 double GuiReceiver::isFullScreen(QString name)
919 QPointer<CvWindow> w = icvFindWindowByName(name);
924 return w->isFullScreen() ? CV_WINDOW_FULLSCREEN : CV_WINDOW_NORMAL;
928 void GuiReceiver::toggleFullScreen(QString name, double arg2)
930 QPointer<CvWindow> w = icvFindWindowByName(name);
935 int flags = (int) arg2;
937 w->toggleFullScreen(flags);
941 void GuiReceiver::createWindow(QString name, int flags)
944 CV_Error(CV_StsNullPtr, "NULL session handler" );
946 // Check the name in the storage
947 if (icvFindWindowByName(name.toLatin1().data()))
953 new CvWindow(name, flags);
957 void GuiReceiver::timeOut()
963 void GuiReceiver::displayInfo(QString name, QString text, int delayms)
965 QPointer<CvWindow> w = icvFindWindowByName(name);
968 w->displayInfo(text, delayms);
972 void GuiReceiver::displayStatusBar(QString name, QString text, int delayms)
974 QPointer<CvWindow> w = icvFindWindowByName(name);
977 w->displayStatusBar(text, delayms);
981 void GuiReceiver::showImage(QString name, void* arr)
983 QPointer<CvWindow> w = icvFindWindowByName(name);
985 if (!w) //as observed in the previous implementation (W32, GTK or Carbon), create a new window is the pointer returned is null
987 cvNamedWindow(name.toLatin1().data());
988 w = icvFindWindowByName(name);
992 return; // keep silence here.
998 mat = cvGetMat(arr, &stub);
1000 cv::Mat im = cv::cvarrToMat(mat);
1001 cv::imshow(name.toUtf8().data(), im);
1005 w->updateImage(arr);
1013 void GuiReceiver::destroyWindow(QString name)
1016 QPointer<CvWindow> w = icvFindWindowByName(name);
1022 //in not-multiThreads mode, looks like the window is hidden but not deleted
1023 //so I do it manually
1024 //otherwise QApplication do it for me if the exec command was executed (in multiThread mode)
1031 void GuiReceiver::destroyAllWindow()
1034 CV_Error(CV_StsNullPtr, "NULL session handler" );
1038 // WARNING: this could even close windows from an external parent app
1039 //#TODO check externalQAppExists and in case it does, close windows carefully,
1040 // i.e. apply the className-check from below...
1041 qApp->closeAllWindows();
1045 bool isWidgetDeleted = true;
1046 while(isWidgetDeleted)
1048 isWidgetDeleted = false;
1049 QWidgetList list = QApplication::topLevelWidgets();
1050 for (int i = 0; i < list.count(); i++)
1052 QObject *obj = list.at(i);
1053 if (obj->metaObject()->className() == QString("CvWindow"))
1056 isWidgetDeleted = true;
1065 void GuiReceiver::moveWindow(QString name, int x, int y)
1067 QPointer<CvWindow> w = icvFindWindowByName(name);
1074 void GuiReceiver::resizeWindow(QString name, int width, int height)
1076 QPointer<CvWindow> w = icvFindWindowByName(name);
1081 w->setViewportSize(QSize(width, height));
1086 void GuiReceiver::enablePropertiesButtonEachWindow()
1088 //For each window, enable window property button
1089 foreach (QWidget* widget, QApplication::topLevelWidgets())
1091 if (widget->isWindow() && !widget->parentWidget()) //is a window without parent
1093 CvWinModel* temp = (CvWinModel*) widget;
1094 if (temp->type == type_CvWindow)
1096 CvWindow* w = (CvWindow*) widget;
1098 //active window properties button
1099 w->enablePropertiesButton();
1106 void GuiReceiver::addButton(QString button_name, int button_type, int initial_button_state, void* on_change, void* userdata)
1108 if (!global_control_panel)
1111 QPointer<CvButtonbar> b;
1113 if (global_control_panel->myLayout->count() == 0) //if that is the first button attach to the control panel, create a new button bar
1115 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1116 enablePropertiesButtonEachWindow();
1121 CvBar* lastbar = (CvBar*) global_control_panel->myLayout->itemAt(global_control_panel->myLayout->count() - 1);
1123 if (lastbar->type == type_CvTrackbar) //if last bar is a trackbar, create a new buttonbar, else, attach to the current bar
1124 b = CvWindow::createButtonBar(button_name); //the bar has the name of the first button attached to it
1126 b = (CvButtonbar*) lastbar;
1130 b->addButton(button_name, (CvButtonCallback) on_change, userdata, button_type, initial_button_state);
1134 void GuiReceiver::addSlider2(QString bar_name, QString window_name, void* value, int count, void* on_change, void *userdata)
1136 QBoxLayout *layout = NULL;
1137 QPointer<CvWindow> w;
1139 if (!window_name.isEmpty())
1141 w = icvFindWindowByName(window_name);
1148 if (global_control_panel)
1149 layout = global_control_panel->myLayout;
1152 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1154 if (t) //trackbar exists
1158 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1160 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1161 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1163 CvWindow::addSlider2(w, bar_name, (int*)value, count, (CvTrackbarCallback2) on_change, userdata);
1167 void GuiReceiver::addSlider(QString bar_name, QString window_name, void* value, int count, void* on_change)
1169 QBoxLayout *layout = NULL;
1170 QPointer<CvWindow> w;
1172 if (!window_name.isEmpty())
1174 w = icvFindWindowByName(window_name);
1181 if (global_control_panel)
1182 layout = global_control_panel->myLayout;
1185 QPointer<CvTrackbar> t = icvFindTrackBarByName(bar_name.toLatin1().data(), window_name.toLatin1().data(), layout);
1187 if (t) //trackbar exists
1191 CV_Error(CV_StsNullPtr, "NULL value pointer" );
1193 if (count <= 0) //count is the max value of the slider, so must be bigger than 0
1194 CV_Error(CV_StsNullPtr, "Max value of the slider must be bigger than 0" );
1196 CvWindow::addSlider(w, bar_name, (int*)value, count, (CvTrackbarCallback) on_change);
1200 int GuiReceiver::start()
1202 return qApp->exec();
1206 void GuiReceiver::setOpenGlDrawCallback(QString name, void* callback, void* userdata)
1208 QPointer<CvWindow> w = icvFindWindowByName(name);
1211 w->setOpenGlDrawCallback((CvOpenGlDrawCallback) callback, userdata);
1214 void GuiReceiver::setOpenGlContext(QString name)
1216 QPointer<CvWindow> w = icvFindWindowByName(name);
1219 w->makeCurrentOpenGlContext();
1222 void GuiReceiver::updateWindow(QString name)
1224 QPointer<CvWindow> w = icvFindWindowByName(name);
1230 double GuiReceiver::isOpenGl(QString name)
1234 QPointer<CvWindow> w = icvFindWindowByName(name);
1237 result = (double) w->isOpenGl();
1243 //////////////////////////////////////////////////////
1247 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback2 on_change, void* data)
1250 callback2 = on_change;
1253 create(arg, name, value, _count);
1257 CvTrackbar::CvTrackbar(CvWindow* arg, QString name, int* value, int _count, CvTrackbarCallback on_change)
1259 callback = on_change;
1263 create(arg, name, value, _count);
1267 void CvTrackbar::create(CvWindow* arg, QString name, int* value, int _count)
1269 type = type_CvTrackbar;
1272 setObjectName(name_bar);
1275 slider = new QSlider(Qt::Horizontal);
1276 slider->setFocusPolicy(Qt::StrongFocus);
1277 slider->setMinimum(0);
1278 slider->setMaximum(_count);
1279 slider->setPageStep(5);
1280 slider->setValue(*value);
1281 slider->setTickPosition(QSlider::TicksBelow);
1284 //Change style of the Slider
1285 //slider->setStyleSheet(str_Trackbar_css);
1287 QFile qss(":/stylesheet-trackbar");
1288 if (qss.open(QFile::ReadOnly))
1290 slider->setStyleSheet(QLatin1String(qss.readAll()));
1295 //this next line does not work if we change the style with a stylesheet, why ? (bug in QT ?)
1296 //slider->setTickPosition(QSlider::TicksBelow);
1297 label = new QPushButton;
1298 label->setFlat(true);
1299 setLabel(slider->value());
1302 QObject::connect(slider, SIGNAL(valueChanged(int)), this, SLOT(update(int)));
1304 QObject::connect(label, SIGNAL(clicked()), this, SLOT(createDialog()));
1306 //label->setStyleSheet("QPushButton:disabled {color: black}");
1308 addWidget(label, Qt::AlignLeft);//name + value
1309 addWidget(slider, Qt::AlignCenter);//slider
1313 void CvTrackbar::createDialog()
1317 //crash if I access the values directly and give them to QInputDialog, so do a copy first.
1318 int value = slider->value();
1319 int step = slider->singleStep();
1320 int min = slider->minimum();
1321 int max = slider->maximum();
1324 #if QT_VERSION >= 0x040500
1325 QInputDialog::getInt
1327 QInputDialog::getInteger
1329 (this->parentWidget(),
1330 tr("Slider %1").arg(name_bar),
1339 slider->setValue(i);
1343 void CvTrackbar::update(int myvalue)
1347 *dataSlider = myvalue;
1356 callback2(myvalue, userdata);
1362 void CvTrackbar::setLabel(int myvalue)
1364 QString nameNormalized = name_bar.leftJustified( 10, ' ', true );
1365 QString valueMaximum = QString("%1").arg(slider->maximum());
1366 QString str = QString("%1 (%2/%3)").arg(nameNormalized).arg(myvalue,valueMaximum.length(),10,QChar('0')).arg(valueMaximum);
1367 label->setText(str);
1371 //////////////////////////////////////////////////////
1375 //here CvButtonbar class
1376 CvButtonbar::CvButtonbar(QWidget* arg, QString arg2)
1378 type = type_CvButtonbar;
1381 setObjectName(name_bar);
1383 group_button = new QButtonGroup(this);
1387 void CvButtonbar::setLabel()
1389 QString nameNormalized = name_bar.leftJustified(10, ' ', true);
1390 label->setText(nameNormalized);
1394 void CvButtonbar::addButton(QString name, CvButtonCallback call, void* userdata, int button_type, int initial_button_state)
1396 QString button_name = name;
1398 if (button_name == "")
1399 button_name = tr("button %1").arg(this->count());
1401 QPointer<QAbstractButton> button;
1403 if (button_type == CV_PUSH_BUTTON)
1404 button = (QAbstractButton*) new CvPushButton(this, button_name,call, userdata);
1406 if (button_type == CV_CHECKBOX)
1407 button = (QAbstractButton*) new CvCheckBox(this, button_name,call, userdata, initial_button_state);
1409 if (button_type == CV_RADIOBOX)
1411 button = (QAbstractButton*) new CvRadioButton(this, button_name,call, userdata, initial_button_state);
1412 group_button->addButton(button);
1417 if (button_type == CV_PUSH_BUTTON)
1418 QObject::connect(button, SIGNAL(clicked(bool)), button, SLOT(callCallBack(bool)));
1420 QObject::connect(button, SIGNAL(toggled(bool)), button, SLOT(callCallBack(bool)));
1422 addWidget(button, Qt::AlignCenter);
1427 //////////////////////////////////////////////////////
1432 CvPushButton::CvPushButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4)
1439 setObjectName(button_name);
1440 setText(button_name);
1447 void CvPushButton::callCallBack(bool checked)
1450 callback(checked, userdata);
1454 CvCheckBox::CvCheckBox(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1461 setObjectName(button_name);
1462 setCheckState((initial_button_state == 1 ? Qt::Checked : Qt::Unchecked));
1463 setText(button_name);
1470 void CvCheckBox::callCallBack(bool checked)
1473 callback(checked, userdata);
1477 CvRadioButton::CvRadioButton(CvButtonbar* arg1, QString arg2, CvButtonCallback arg3, void* arg4, int initial_button_state)
1484 setObjectName(button_name);
1485 setChecked(initial_button_state);
1486 setText(button_name);
1492 void CvRadioButton::callCallBack(bool checked)
1495 callback(checked, userdata);
1499 //////////////////////////////////////////////////////
1503 //here CvWinProperties class
1504 CvWinProperties::CvWinProperties(QString name_paraWindow, QObject* /*parent*/)
1506 //setParent(parent);
1507 type = type_CvWinProperties;
1508 setWindowFlags(Qt::Tool);
1509 setContentsMargins(0, 0, 0, 0);
1510 setWindowTitle(name_paraWindow);
1511 setObjectName(name_paraWindow);
1514 myLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1515 myLayout->setObjectName(QString::fromUtf8("boxLayout"));
1516 myLayout->setContentsMargins(0, 0, 0, 0);
1517 myLayout->setSpacing(0);
1518 myLayout->setMargin(0);
1519 myLayout->setSizeConstraint(QLayout::SetFixedSize);
1520 setLayout(myLayout);
1526 void CvWinProperties::closeEvent(QCloseEvent* e)
1528 e->accept(); //intersept the close event (not sure I really need it)
1529 //an hide event is also sent. I will intercept it and do some processing
1533 void CvWinProperties::showEvent(QShowEvent* evnt)
1535 //why -1,-1 ?: do this trick because the first time the code is run,
1536 //no value pos was saved so we let Qt move the window in the middle of its parent (event ignored).
1537 //then hide will save the last position and thus, we want to retreive it (event accepted).
1538 QPoint mypos(-1, -1);
1539 QSettings settings("OpenCV2", objectName());
1540 mypos = settings.value("pos", mypos).toPoint();
1554 void CvWinProperties::hideEvent(QHideEvent* evnt)
1556 QSettings settings("OpenCV2", objectName());
1557 settings.setValue("pos", pos()); //there is an offset of 6 pixels (so the window's position is wrong -- why ?)
1562 CvWinProperties::~CvWinProperties()
1564 //clear the setting pos
1565 QSettings settings("OpenCV2", objectName());
1566 settings.remove("pos");
1570 //////////////////////////////////////////////////////
1574 CvWindow::CvWindow(QString name, int arg2)
1576 type = type_CvWindow;
1578 param_flags = arg2 & 0x0000000F;
1579 param_gui_mode = arg2 & 0x000000F0;
1580 param_ratio_mode = arg2 & 0x00000F00;
1582 //setAttribute(Qt::WA_DeleteOnClose); //in other case, does not release memory
1583 setContentsMargins(0, 0, 0, 0);
1584 setWindowTitle(name);
1585 setObjectName(name);
1587 setFocus( Qt::PopupFocusReason ); //#1695 arrow keys are not received without the explicit focus
1590 setMinimumSize(1, 1);
1592 //1: create control panel
1593 if (!global_control_panel)
1594 global_control_panel = createParameterWindow();
1598 createGlobalLayout();
1601 #ifndef HAVE_QT_OPENGL
1602 if (arg2 & CV_WINDOW_OPENGL)
1603 CV_Error( CV_OpenGlNotSupported, "Library was built without OpenGL support" );
1604 mode_display = CV_MODE_NORMAL;
1606 mode_display = arg2 & CV_WINDOW_OPENGL ? CV_MODE_OPENGL : CV_MODE_NORMAL;
1607 if (mode_display == CV_MODE_OPENGL)
1608 param_gui_mode = CV_GUI_NORMAL;
1612 //4: shortcuts and actions
1613 //5: toolBar and statusbar
1614 if (param_gui_mode == CV_GUI_EXPANDED)
1623 //Now attach everything
1625 myGlobalLayout->addWidget(myToolBar, Qt::AlignCenter);
1627 myGlobalLayout->addWidget(myView->getWidget(), Qt::AlignCenter);
1629 myGlobalLayout->addLayout(myBarLayout, Qt::AlignCenter);
1632 myGlobalLayout->addWidget(myStatusBar, Qt::AlignCenter);
1634 setLayout(myGlobalLayout);
1639 CvWindow::~CvWindow()
1642 guiMainThread->isLastWindow();
1646 void CvWindow::setMouseCallBack(CvMouseCallback callback, void* param)
1648 myView->setMouseCallBack(callback, param);
1652 void CvWindow::writeSettings()
1654 //organisation and application's name
1655 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1657 settings.setValue("pos", pos());
1658 settings.setValue("size", size());
1659 settings.setValue("mode_resize" ,param_flags);
1660 settings.setValue("mode_gui", param_gui_mode);
1662 myView->writeSettings(settings);
1664 icvSaveTrackbars(&settings);
1666 if (global_control_panel)
1668 icvSaveControlPanel();
1669 settings.setValue("posPanel", global_control_panel->pos());
1675 //TODO: load CV_GUI flag (done) and act accordingly (create win property if needed and attach trackbars)
1676 void CvWindow::readSettings()
1678 //organisation and application's name
1679 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName());
1681 QPoint _pos = settings.value("pos", QPoint(200, 200)).toPoint();
1682 QSize _size = settings.value("size", QSize(400, 400)).toSize();
1684 param_flags = settings.value("mode_resize", param_flags).toInt();
1685 param_gui_mode = settings.value("mode_gui", param_gui_mode).toInt();
1687 param_flags = settings.value("mode_resize", param_flags).toInt();
1689 myView->readSettings(settings);
1692 icvLoadTrackbars(&settings);
1697 if (global_control_panel)
1699 icvLoadControlPanel();
1700 global_control_panel->move(settings.value("posPanel", global_control_panel->pos()).toPoint());
1705 double CvWindow::getRatio()
1707 return myView->getRatio();
1711 void CvWindow::setRatio(int flags)
1713 myView->setRatio(flags);
1717 int CvWindow::getPropWindow()
1723 void CvWindow::setPropWindow(int flags)
1725 if (param_flags == flags) //nothing to do
1730 case CV_WINDOW_NORMAL:
1731 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1732 param_flags = flags;
1736 case CV_WINDOW_AUTOSIZE:
1737 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1738 param_flags = flags;
1747 void CvWindow::toggleFullScreen(int flags)
1749 if (isFullScreen() && flags == CV_WINDOW_NORMAL)
1756 if (!isFullScreen() && flags == CV_WINDOW_FULLSCREEN)
1765 void CvWindow::updateImage(void* arr)
1767 myView->updateImage(arr);
1771 void CvWindow::displayInfo(QString text, int delayms)
1773 myView->startDisplayInfo(text, delayms);
1777 void CvWindow::displayStatusBar(QString text, int delayms)
1780 myStatusBar->showMessage(text, delayms);
1784 void CvWindow::enablePropertiesButton()
1786 if (!vect_QActions.empty())
1787 vect_QActions[9]->setDisabled(false);
1791 CvButtonbar* CvWindow::createButtonBar(QString name_bar)
1793 QPointer<CvButtonbar> t = new CvButtonbar(global_control_panel, name_bar);
1794 t->setAlignment(Qt::AlignHCenter);
1796 QPointer<QBoxLayout> myLayout = global_control_panel->myLayout;
1798 myLayout->insertLayout(myLayout->count(), t);
1804 void CvWindow::addSlider(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback on_change)
1806 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change);
1807 t->setAlignment(Qt::AlignHCenter);
1809 QPointer<QBoxLayout> myLayout;
1813 myLayout = w->myBarLayout;
1817 myLayout = global_control_panel->myLayout;
1819 //if first one, enable control panel
1820 if (myLayout->count() == 0)
1821 guiMainThread->enablePropertiesButtonEachWindow();
1824 myLayout->insertLayout(myLayout->count(), t);
1828 void CvWindow::addSlider2(CvWindow* w, QString name, int* value, int count, CvTrackbarCallback2 on_change, void* userdata)
1830 QPointer<CvTrackbar> t = new CvTrackbar(w, name, value, count, on_change, userdata);
1831 t->setAlignment(Qt::AlignHCenter);
1833 QPointer<QBoxLayout> myLayout;
1837 myLayout = w->myBarLayout;
1841 myLayout = global_control_panel->myLayout;
1843 //if first one, enable control panel
1844 if (myLayout->count() == 0)
1845 guiMainThread->enablePropertiesButtonEachWindow();
1848 myLayout->insertLayout(myLayout->count(), t);
1852 void CvWindow::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
1854 myView->setOpenGlDrawCallback(callback, userdata);
1858 void CvWindow::makeCurrentOpenGlContext()
1860 myView->makeCurrentOpenGlContext();
1864 void CvWindow::updateGl()
1870 bool CvWindow::isOpenGl()
1872 return mode_display == CV_MODE_OPENGL;
1876 void CvWindow::setViewportSize(QSize _size)
1878 myView->getWidget()->resize(_size);
1879 myView->setSize(_size);
1883 void CvWindow::createBarLayout()
1885 myBarLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1886 myBarLayout->setObjectName(QString::fromUtf8("barLayout"));
1887 myBarLayout->setContentsMargins(0, 0, 0, 0);
1888 myBarLayout->setSpacing(0);
1889 myBarLayout->setMargin(0);
1893 void CvWindow::createGlobalLayout()
1895 myGlobalLayout = new QBoxLayout(QBoxLayout::TopToBottom);
1896 myGlobalLayout->setObjectName(QString::fromUtf8("boxLayout"));
1897 myGlobalLayout->setContentsMargins(0, 0, 0, 0);
1898 myGlobalLayout->setSpacing(0);
1899 myGlobalLayout->setMargin(0);
1900 setMinimumSize(1, 1);
1902 if (param_flags == CV_WINDOW_AUTOSIZE)
1903 myGlobalLayout->setSizeConstraint(QLayout::SetFixedSize);
1904 else if (param_flags == CV_WINDOW_NORMAL)
1905 myGlobalLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
1909 void CvWindow::createView()
1911 #ifdef HAVE_QT_OPENGL
1913 myView = new OpenGlViewPort(this);
1916 myView = new DefaultViewPort(this, param_ratio_mode);
1920 void CvWindow::createActions()
1922 vect_QActions.resize(10);
1924 QWidget* view = myView->getWidget();
1926 //if the shortcuts are changed in window_QT.h, we need to update the tooltip manually
1927 vect_QActions[0] = new QAction(QIcon(":/left-icon"), "Panning left (CTRL+arrowLEFT)", this);
1928 vect_QActions[0]->setIconVisibleInMenu(true);
1929 QObject::connect(vect_QActions[0], SIGNAL(triggered()), view, SLOT(siftWindowOnLeft()));
1931 vect_QActions[1] = new QAction(QIcon(":/right-icon"), "Panning right (CTRL+arrowRIGHT)", this);
1932 vect_QActions[1]->setIconVisibleInMenu(true);
1933 QObject::connect(vect_QActions[1], SIGNAL(triggered()), view, SLOT(siftWindowOnRight()));
1935 vect_QActions[2] = new QAction(QIcon(":/up-icon"), "Panning up (CTRL+arrowUP)", this);
1936 vect_QActions[2]->setIconVisibleInMenu(true);
1937 QObject::connect(vect_QActions[2], SIGNAL(triggered()), view, SLOT(siftWindowOnUp()));
1939 vect_QActions[3] = new QAction(QIcon(":/down-icon"), "Panning down (CTRL+arrowDOWN)", this);
1940 vect_QActions[3]->setIconVisibleInMenu(true);
1941 QObject::connect(vect_QActions[3], SIGNAL(triggered()), view, SLOT(siftWindowOnDown()) );
1943 vect_QActions[4] = new QAction(QIcon(":/zoom_x1-icon"), "Zoom x1 (CTRL+P)", this);
1944 vect_QActions[4]->setIconVisibleInMenu(true);
1945 QObject::connect(vect_QActions[4], SIGNAL(triggered()), view, SLOT(resetZoom()));
1947 vect_QActions[5] = new QAction(QIcon(":/imgRegion-icon"), tr("Zoom x%1 (see label) (CTRL+X)").arg(threshold_zoom_img_region), this);
1948 vect_QActions[5]->setIconVisibleInMenu(true);
1949 QObject::connect(vect_QActions[5], SIGNAL(triggered()), view, SLOT(imgRegion()));
1951 vect_QActions[6] = new QAction(QIcon(":/zoom_in-icon"), "Zoom in (CTRL++)", this);
1952 vect_QActions[6]->setIconVisibleInMenu(true);
1953 QObject::connect(vect_QActions[6], SIGNAL(triggered()), view, SLOT(ZoomIn()));
1955 vect_QActions[7] = new QAction(QIcon(":/zoom_out-icon"), "Zoom out (CTRL+-)", this);
1956 vect_QActions[7]->setIconVisibleInMenu(true);
1957 QObject::connect(vect_QActions[7], SIGNAL(triggered()), view, SLOT(ZoomOut()));
1959 vect_QActions[8] = new QAction(QIcon(":/save-icon"), "Save current image (CTRL+S)", this);
1960 vect_QActions[8]->setIconVisibleInMenu(true);
1961 QObject::connect(vect_QActions[8], SIGNAL(triggered()), view, SLOT(saveView()));
1963 vect_QActions[9] = new QAction(QIcon(":/properties-icon"), "Display properties window (CTRL+P)", this);
1964 vect_QActions[9]->setIconVisibleInMenu(true);
1965 QObject::connect(vect_QActions[9], SIGNAL(triggered()), this, SLOT(displayPropertiesWin()));
1967 if (global_control_panel->myLayout->count() == 0)
1968 vect_QActions[9]->setDisabled(true);
1972 void CvWindow::createShortcuts()
1974 vect_QShortcuts.resize(10);
1976 QWidget* view = myView->getWidget();
1978 vect_QShortcuts[0] = new QShortcut(shortcut_panning_left, this);
1979 QObject::connect(vect_QShortcuts[0], SIGNAL(activated()), view, SLOT(siftWindowOnLeft()));
1981 vect_QShortcuts[1] = new QShortcut(shortcut_panning_right, this);
1982 QObject::connect(vect_QShortcuts[1], SIGNAL(activated()), view, SLOT(siftWindowOnRight()));
1984 vect_QShortcuts[2] = new QShortcut(shortcut_panning_up, this);
1985 QObject::connect(vect_QShortcuts[2], SIGNAL(activated()), view, SLOT(siftWindowOnUp()));
1987 vect_QShortcuts[3] = new QShortcut(shortcut_panning_down, this);
1988 QObject::connect(vect_QShortcuts[3], SIGNAL(activated()), view, SLOT(siftWindowOnDown()));
1990 vect_QShortcuts[4] = new QShortcut(shortcut_zoom_normal, this);
1991 QObject::connect(vect_QShortcuts[4], SIGNAL(activated()), view, SLOT(resetZoom()));
1993 vect_QShortcuts[5] = new QShortcut(shortcut_zoom_imgRegion, this);
1994 QObject::connect(vect_QShortcuts[5], SIGNAL(activated()), view, SLOT(imgRegion()));
1996 vect_QShortcuts[6] = new QShortcut(shortcut_zoom_in, this);
1997 QObject::connect(vect_QShortcuts[6], SIGNAL(activated()), view, SLOT(ZoomIn()));
1999 vect_QShortcuts[7] = new QShortcut(shortcut_zoom_out, this);
2000 QObject::connect(vect_QShortcuts[7], SIGNAL(activated()), view, SLOT(ZoomOut()));
2002 vect_QShortcuts[8] = new QShortcut(shortcut_save_img, this);
2003 QObject::connect(vect_QShortcuts[8], SIGNAL(activated()), view, SLOT(saveView()));
2005 vect_QShortcuts[9] = new QShortcut(shortcut_properties_win, this);
2006 QObject::connect(vect_QShortcuts[9], SIGNAL(activated()), this, SLOT(displayPropertiesWin()));
2010 void CvWindow::createToolBar()
2012 myToolBar = new QToolBar(this);
2013 myToolBar->setFloatable(false); //is not a window
2014 myToolBar->setFixedHeight(28);
2015 myToolBar->setMinimumWidth(1);
2017 foreach (QAction *a, vect_QActions)
2018 myToolBar->addAction(a);
2022 void CvWindow::createStatusBar()
2024 myStatusBar = new QStatusBar(this);
2025 myStatusBar->setSizeGripEnabled(false);
2026 myStatusBar->setFixedHeight(20);
2027 myStatusBar->setMinimumWidth(1);
2028 myStatusBar_msg = new QLabel;
2030 //I comment this because if we change the style, myview (the picture)
2031 //will not be the correct size anymore (will lost 2 pixel because of the borders)
2033 //myStatusBar_msg->setFrameStyle(QFrame::Raised);
2035 myStatusBar_msg->setAlignment(Qt::AlignHCenter);
2036 myStatusBar->addWidget(myStatusBar_msg);
2040 void CvWindow::hideTools()
2046 myStatusBar->hide();
2048 if (global_control_panel)
2049 global_control_panel->hide();
2053 void CvWindow::showTools()
2059 myStatusBar->show();
2063 CvWinProperties* CvWindow::createParameterWindow()
2065 QString name_paraWindow = QFileInfo(QApplication::applicationFilePath()).fileName() + " settings";
2067 CvWinProperties* result = new CvWinProperties(name_paraWindow, guiMainThread);
2073 void CvWindow::displayPropertiesWin()
2075 if (global_control_panel->isHidden())
2076 global_control_panel->show();
2078 global_control_panel->hide();
2082 //Need more test here !
2083 void CvWindow::keyPressEvent(QKeyEvent *evnt)
2085 //see http://doc.trolltech.com/4.6/qt.html#Key-enum
2086 int key = evnt->key();
2088 Qt::Key qtkey = static_cast<Qt::Key>(key);
2089 char asciiCode = QTest::keyToAscii(qtkey);
2091 key = static_cast<int>(asciiCode);
2093 key = evnt->nativeVirtualKey(); //same codes as returned by GTK-based backend
2095 //control plus (Z, +, -, up, down, left, right) are used for zoom/panning functions
2096 if (evnt->modifiers() != Qt::ControlModifier)
2101 key_pressed.wakeAll();
2105 QWidget::keyPressEvent(evnt);
2109 void CvWindow::icvLoadControlPanel()
2111 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName() + " control panel");
2113 int bsize = settings.beginReadArray("bars");
2115 if (bsize == global_control_panel->myLayout->layout()->count())
2117 for (int i = 0; i < bsize; ++i)
2119 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2120 settings.setArrayIndex(i);
2121 if (t->type == type_CvTrackbar)
2123 if (t->name_bar == settings.value("namebar").toString())
2125 ((CvTrackbar*)t)->slider->setValue(settings.value("valuebar").toInt());
2128 if (t->type == type_CvButtonbar)
2130 int subsize = settings.beginReadArray(QString("buttonbar")+i);
2132 if ( subsize == ((CvButtonbar*)t)->layout()->count() )
2133 icvLoadButtonbar((CvButtonbar*)t,&settings);
2135 settings.endArray();
2140 settings.endArray();
2144 void CvWindow::icvSaveControlPanel()
2146 QSettings settings("OpenCV2", QFileInfo(QApplication::applicationFilePath()).fileName()+" control panel");
2148 settings.beginWriteArray("bars");
2150 for (int i = 0; i < global_control_panel->myLayout->layout()->count(); ++i)
2152 CvBar* t = (CvBar*) global_control_panel->myLayout->layout()->itemAt(i);
2153 settings.setArrayIndex(i);
2154 if (t->type == type_CvTrackbar)
2156 settings.setValue("namebar", QString(t->name_bar));
2157 settings.setValue("valuebar",((CvTrackbar*)t)->slider->value());
2159 if (t->type == type_CvButtonbar)
2161 settings.beginWriteArray(QString("buttonbar")+i);
2162 icvSaveButtonbar((CvButtonbar*)t,&settings);
2163 settings.endArray();
2167 settings.endArray();
2171 void CvWindow::icvSaveButtonbar(CvButtonbar* b, QSettings* settings)
2173 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2175 settings->setArrayIndex(i);
2177 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2178 QString myclass(QLatin1String(temp->metaObject()->className()));
2180 if (myclass == "CvPushButton")
2182 CvPushButton* button = (CvPushButton*) temp;
2183 settings->setValue("namebutton", button->text());
2184 settings->setValue("valuebutton", int(button->isChecked()));
2186 else if (myclass == "CvCheckBox")
2188 CvCheckBox* button = (CvCheckBox*) temp;
2189 settings->setValue("namebutton", button->text());
2190 settings->setValue("valuebutton", int(button->isChecked()));
2192 else if (myclass == "CvRadioButton")
2194 CvRadioButton* button = (CvRadioButton*) temp;
2195 settings->setValue("namebutton", button->text());
2196 settings->setValue("valuebutton", int(button->isChecked()));
2202 void CvWindow::icvLoadButtonbar(CvButtonbar* b, QSettings* settings)
2204 for (int i = 0, count = b->layout()->count(); i < count; ++i)
2206 settings->setArrayIndex(i);
2208 QWidget* temp = (QWidget*) b->layout()->itemAt(i)->widget();
2209 QString myclass(QLatin1String(temp->metaObject()->className()));
2211 if (myclass == "CvPushButton")
2213 CvPushButton* button = (CvPushButton*) temp;
2215 if (button->text() == settings->value("namebutton").toString())
2216 button->setChecked(settings->value("valuebutton").toInt());
2218 else if (myclass == "CvCheckBox")
2220 CvCheckBox* button = (CvCheckBox*) temp;
2222 if (button->text() == settings->value("namebutton").toString())
2223 button->setChecked(settings->value("valuebutton").toInt());
2225 else if (myclass == "CvRadioButton")
2227 CvRadioButton* button = (CvRadioButton*) temp;
2229 if (button->text() == settings->value("namebutton").toString())
2230 button->setChecked(settings->value("valuebutton").toInt());
2237 void CvWindow::icvLoadTrackbars(QSettings* settings)
2239 int bsize = settings->beginReadArray("trackbars");
2241 //trackbar are saved in the same order, so no need to use icvFindTrackbarByName
2243 if (myBarLayout->layout()->count() == bsize) //if not the same number, the window saved and loaded is not the same (nb trackbar not equal)
2245 for (int i = 0; i < bsize; ++i)
2247 settings->setArrayIndex(i);
2249 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2251 if (t->name_bar == settings->value("name").toString())
2252 t->slider->setValue(settings->value("value").toInt());
2257 settings->endArray();
2261 void CvWindow::icvSaveTrackbars(QSettings* settings)
2263 settings->beginWriteArray("trackbars");
2265 for (int i = 0; i < myBarLayout->layout()->count(); ++i)
2267 settings->setArrayIndex(i);
2269 CvTrackbar* t = (CvTrackbar*) myBarLayout->layout()->itemAt(i);
2271 settings->setValue("name", t->name_bar);
2272 settings->setValue("value", t->slider->value());
2275 settings->endArray();
2279 //////////////////////////////////////////////////////
2283 DefaultViewPort::DefaultViewPort(CvWindow* arg, int arg2) : QGraphicsView(arg), image2Draw_mat(0)
2285 centralWidget = arg;
2286 param_keepRatio = arg2;
2288 setContentsMargins(0, 0, 0, 0);
2289 setMinimumSize(1, 1);
2290 setAlignment(Qt::AlignHCenter);
2292 setObjectName(QString::fromUtf8("graphicsView"));
2294 timerDisplay = new QTimer(this);
2295 timerDisplay->setSingleShot(true);
2296 connect(timerDisplay, SIGNAL(timeout()), this, SLOT(stopDisplayInfo()));
2299 positionGrabbing = QPointF(0, 0);
2300 positionCorners = QRect(0, 0, size().width(), size().height());
2304 mouseCoordinate = QPoint(-1, -1);
2307 setStyleSheet( "QGraphicsView { border-style: none; }" );
2309 image2Draw_mat = cvCreateMat(viewport()->height(), viewport()->width(), CV_8UC3);
2310 cvZero(image2Draw_mat);
2312 nbChannelOriginImage = 0;
2314 setInteractive(false);
2315 setMouseTracking(true); //receive mouse event everytime
2319 DefaultViewPort::~DefaultViewPort()
2322 cvReleaseMat(&image2Draw_mat);
2326 QWidget* DefaultViewPort::getWidget()
2332 void DefaultViewPort::setMouseCallBack(CvMouseCallback m, void* param)
2336 on_mouse_param = param;
2339 void DefaultViewPort::writeSettings(QSettings& settings)
2341 settings.setValue("matrix_view.m11", param_matrixWorld.m11());
2342 settings.setValue("matrix_view.m12", param_matrixWorld.m12());
2343 settings.setValue("matrix_view.m13", param_matrixWorld.m13());
2344 settings.setValue("matrix_view.m21", param_matrixWorld.m21());
2345 settings.setValue("matrix_view.m22", param_matrixWorld.m22());
2346 settings.setValue("matrix_view.m23", param_matrixWorld.m23());
2347 settings.setValue("matrix_view.m31", param_matrixWorld.m31());
2348 settings.setValue("matrix_view.m32", param_matrixWorld.m32());
2349 settings.setValue("matrix_view.m33", param_matrixWorld.m33());
2353 void DefaultViewPort::readSettings(QSettings& settings)
2355 qreal m11 = settings.value("matrix_view.m11", param_matrixWorld.m11()).toDouble();
2356 qreal m12 = settings.value("matrix_view.m12", param_matrixWorld.m12()).toDouble();
2357 qreal m13 = settings.value("matrix_view.m13", param_matrixWorld.m13()).toDouble();
2358 qreal m21 = settings.value("matrix_view.m21", param_matrixWorld.m21()).toDouble();
2359 qreal m22 = settings.value("matrix_view.m22", param_matrixWorld.m22()).toDouble();
2360 qreal m23 = settings.value("matrix_view.m23", param_matrixWorld.m23()).toDouble();
2361 qreal m31 = settings.value("matrix_view.m31", param_matrixWorld.m31()).toDouble();
2362 qreal m32 = settings.value("matrix_view.m32", param_matrixWorld.m32()).toDouble();
2363 qreal m33 = settings.value("matrix_view.m33", param_matrixWorld.m33()).toDouble();
2365 param_matrixWorld = QTransform(m11, m12, m13, m21, m22, m23, m31, m32, m33);
2369 double DefaultViewPort::getRatio()
2371 return param_keepRatio;
2375 void DefaultViewPort::setRatio(int flags)
2377 if (getRatio() == flags) //nothing to do
2381 if (flags == CV_WINDOW_FREERATIO || flags == CV_WINDOW_KEEPRATIO)
2383 centralWidget->param_ratio_mode = flags;
2384 param_keepRatio = flags;
2386 viewport()->update();
2391 void DefaultViewPort::updateImage(const CvArr* arr)
2398 if (CV_IS_IMAGE_HDR(arr))
2399 origin = ((IplImage*)arr)->origin;
2401 mat = cvGetMat(arr, &stub);
2403 if (!image2Draw_mat || !CV_ARE_SIZES_EQ(image2Draw_mat, mat))
2406 cvReleaseMat(&image2Draw_mat);
2408 //the image in ipl (to do a deep copy with cvCvtColor)
2409 image2Draw_mat = cvCreateMat(mat->rows, mat->cols, CV_8UC3);
2410 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows, image2Draw_mat->step, QImage::Format_RGB888);
2412 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2413 ratioX = width() / float(image2Draw_mat->cols);
2414 ratioY = height() / float(image2Draw_mat->rows);
2418 nbChannelOriginImage = cvGetElemType(mat);
2420 cvConvertImage(mat, image2Draw_mat, (origin != 0 ? CV_CVTIMG_FLIP : 0) + CV_CVTIMG_SWAP_RB);
2422 viewport()->update();
2426 void DefaultViewPort::startDisplayInfo(QString text, int delayms)
2428 if (timerDisplay->isActive())
2432 if (delayms > 0) timerDisplay->start(delayms);
2437 void DefaultViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback /*callback*/, void* /*userdata*/)
2439 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2443 void DefaultViewPort::makeCurrentOpenGlContext()
2445 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2449 void DefaultViewPort::updateGl()
2451 CV_Error(CV_OpenGlNotSupported, "Window doesn't support OpenGL");
2455 //Note: move 2 percent of the window
2456 void DefaultViewPort::siftWindowOnLeft()
2458 float delta = 2 * width() / (100.0 * param_matrixWorld.m11());
2459 moveView(QPointF(delta, 0));
2463 //Note: move 2 percent of the window
2464 void DefaultViewPort::siftWindowOnRight()
2466 float delta = -2 * width() / (100.0 * param_matrixWorld.m11());
2467 moveView(QPointF(delta, 0));
2471 //Note: move 2 percent of the window
2472 void DefaultViewPort::siftWindowOnUp()
2474 float delta = 2 * height() / (100.0 * param_matrixWorld.m11());
2475 moveView(QPointF(0, delta));
2479 //Note: move 2 percent of the window
2480 void DefaultViewPort::siftWindowOnDown()
2482 float delta = -2 * height() / (100.0 * param_matrixWorld.m11());
2483 moveView(QPointF(0, delta));
2487 void DefaultViewPort::imgRegion()
2489 scaleView((threshold_zoom_img_region / param_matrixWorld.m11() - 1) * 5, QPointF(size().width() / 2, size().height() / 2));
2493 void DefaultViewPort::resetZoom()
2495 param_matrixWorld.reset();
2496 controlImagePosition();
2500 void DefaultViewPort::ZoomIn()
2502 scaleView(0.5, QPointF(size().width() / 2, size().height() / 2));
2506 void DefaultViewPort::ZoomOut()
2508 scaleView(-0.5, QPointF(size().width() / 2, size().height() / 2));
2512 //can save as JPG, JPEG, BMP, PNG
2513 void DefaultViewPort::saveView()
2515 QDate date_d = QDate::currentDate();
2516 QString date_s = date_d.toString("dd.MM.yyyy");
2517 QString name_s = centralWidget->windowTitle() + "_screenshot_" + date_s;
2519 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File %1").arg(name_s), name_s + ".png", tr("Images (*.png *.jpg *.bmp *.jpeg)"));
2521 if (!fileName.isEmpty()) //save the picture
2523 QString extension = fileName.right(3);
2525 // Create a new pixmap to render the viewport into
2526 QPixmap viewportPixmap(viewport()->size());
2527 viewport()->render(&viewportPixmap);
2530 if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0)
2532 viewportPixmap.save(fileName, "PNG");
2536 if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0)
2538 viewportPixmap.save(fileName, "JPG");
2542 if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0)
2544 viewportPixmap.save(fileName, "BMP");
2548 if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0)
2550 viewportPixmap.save(fileName, "JPEG");
2554 CV_Error(CV_StsNullPtr, "file extension not recognized, please choose between JPG, JPEG, BMP or PNG");
2559 void DefaultViewPort::contextMenuEvent(QContextMenuEvent* evnt)
2561 if (centralWidget->vect_QActions.size() > 0)
2565 foreach (QAction *a, centralWidget->vect_QActions)
2568 menu.exec(evnt->globalPos());
2573 void DefaultViewPort::resizeEvent(QResizeEvent* evnt)
2575 controlImagePosition();
2577 //use to compute mouse coordinate, I need to update the ratio here and in resizeEvent
2578 ratioX = width() / float(image2Draw_mat->cols);
2579 ratioY = height() / float(image2Draw_mat->rows);
2581 if (param_keepRatio == CV_WINDOW_KEEPRATIO)//to keep the same aspect ratio
2583 QSize newSize = QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2584 newSize.scale(evnt->size(), Qt::KeepAspectRatio);
2586 //imageWidth/imageHeight = newWidth/newHeight +/- epsilon
2587 //ratioX = ratioY +/- epsilon
2588 //||ratioX - ratioY|| = epsilon
2589 if (fabs(ratioX - ratioY) * 100 > ratioX) //avoid infinity loop / epsilon = 1% of ratioX
2593 //move to the middle
2594 //newSize get the delta offset to place the picture in the middle of its parent
2595 newSize = (evnt->size() - newSize) / 2;
2597 //if the toolbar is displayed, avoid drawing myview on top of it
2598 if (centralWidget->myToolBar)
2599 if(!centralWidget->myToolBar->isHidden())
2600 newSize += QSize(0, centralWidget->myToolBar->height());
2602 move(newSize.width(), newSize.height());
2606 return QGraphicsView::resizeEvent(evnt);
2610 void DefaultViewPort::wheelEvent(QWheelEvent* evnt)
2612 scaleView(evnt->delta() / 240.0, evnt->pos());
2613 viewport()->update();
2617 void DefaultViewPort::mousePressEvent(QMouseEvent* evnt)
2619 int cv_event = -1, flags = 0;
2620 QPoint pt = evnt->pos();
2622 //icvmouseHandler: pass parameters for cv_event, flags
2623 icvmouseHandler(evnt, mouse_down, cv_event, flags);
2624 icvmouseProcessing(QPointF(pt), cv_event, flags);
2626 if (param_matrixWorld.m11()>1)
2628 setCursor(Qt::ClosedHandCursor);
2629 positionGrabbing = evnt->pos();
2632 QWidget::mousePressEvent(evnt);
2636 void DefaultViewPort::mouseReleaseEvent(QMouseEvent* evnt)
2638 int cv_event = -1, flags = 0;
2639 QPoint pt = evnt->pos();
2641 //icvmouseHandler: pass parameters for cv_event, flags
2642 icvmouseHandler(evnt, mouse_up, cv_event, flags);
2643 icvmouseProcessing(QPointF(pt), cv_event, flags);
2645 if (param_matrixWorld.m11()>1)
2646 setCursor(Qt::OpenHandCursor);
2648 QWidget::mouseReleaseEvent(evnt);
2652 void DefaultViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
2654 int cv_event = -1, flags = 0;
2655 QPoint pt = evnt->pos();
2657 //icvmouseHandler: pass parameters for cv_event, flags
2658 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
2659 icvmouseProcessing(QPointF(pt), cv_event, flags);
2661 QWidget::mouseDoubleClickEvent(evnt);
2665 void DefaultViewPort::mouseMoveEvent(QMouseEvent* evnt)
2667 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
2668 QPoint pt = evnt->pos();
2670 //icvmouseHandler: pass parameters for cv_event, flags
2671 icvmouseHandler(evnt, mouse_move, cv_event, flags);
2672 icvmouseProcessing(QPointF(pt), cv_event, flags);
2674 if (param_matrixWorld.m11() > 1 && evnt->buttons() == Qt::LeftButton)
2676 QPointF dxy = (pt - positionGrabbing)/param_matrixWorld.m11();
2677 positionGrabbing = evnt->pos();
2681 //I update the statusbar here because if the user does a cvWaitkey(0) (like with inpaint.cpp)
2682 //the status bar will only be repaint when a click occurs.
2683 if (centralWidget->myStatusBar)
2684 viewport()->update();
2686 QWidget::mouseMoveEvent(evnt);
2690 void DefaultViewPort::paintEvent(QPaintEvent* evnt)
2692 QPainter myPainter(viewport());
2693 myPainter.setWorldTransform(param_matrixWorld);
2697 //Now disable matrixWorld for overlay display
2698 myPainter.setWorldMatrixEnabled(false);
2700 //overlay pixel values if zoomed in far enough
2701 if (param_matrixWorld.m11()*ratioX >= threshold_zoom_img_region &&
2702 param_matrixWorld.m11()*ratioY >= threshold_zoom_img_region)
2704 drawImgRegion(&myPainter);
2707 //in mode zoom/panning
2708 if (param_matrixWorld.m11() > 1)
2710 drawViewOverview(&myPainter);
2713 //for information overlay
2715 drawInstructions(&myPainter);
2718 if (centralWidget->myStatusBar)
2721 QGraphicsView::paintEvent(evnt);
2725 void DefaultViewPort::stopDisplayInfo()
2727 timerDisplay->stop();
2732 inline bool DefaultViewPort::isSameSize(IplImage* img1, IplImage* img2)
2734 return img1->width == img2->width && img1->height == img2->height;
2738 void DefaultViewPort::controlImagePosition()
2740 qreal left, top, right, bottom;
2742 //after check top-left, bottom right corner to avoid getting "out" during zoom/panning
2743 param_matrixWorld.map(0,0,&left,&top);
2747 param_matrixWorld.translate(-left,0);
2752 param_matrixWorld.translate(0,-top);
2757 QSize sizeImage = size();
2758 param_matrixWorld.map(sizeImage.width(),sizeImage.height(),&right,&bottom);
2759 if (right < sizeImage.width())
2761 param_matrixWorld.translate(sizeImage.width()-right,0);
2762 right = sizeImage.width();
2764 if (bottom < sizeImage.height())
2766 param_matrixWorld.translate(0,sizeImage.height()-bottom);
2767 bottom = sizeImage.height();
2770 //save corner position
2771 positionCorners.setTopLeft(QPoint(left,top));
2772 positionCorners.setBottomRight(QPoint(right,bottom));
2773 //save also the inv matrix
2774 matrixWorld_inv = param_matrixWorld.inverted();
2776 //viewport()->update();
2779 void DefaultViewPort::moveView(QPointF delta)
2781 param_matrixWorld.translate(delta.x(),delta.y());
2782 controlImagePosition();
2783 viewport()->update();
2786 //factor is -0.5 (zoom out) or 0.5 (zoom in)
2787 void DefaultViewPort::scaleView(qreal factor,QPointF center)
2789 factor/=5;//-0.1 <-> 0.1
2790 factor+=1;//0.9 <-> 1.1
2792 //limit zoom out ---
2793 if (param_matrixWorld.m11()==1 && factor < 1)
2796 if (param_matrixWorld.m11()*factor<1)
2797 factor = 1/param_matrixWorld.m11();
2800 //limit zoom int ---
2801 if (param_matrixWorld.m11()>100 && factor > 1)
2804 //inverse the transform
2806 matrixWorld_inv.map(center.x(),center.y(),&a,&b);
2808 param_matrixWorld.translate(a-factor*a,b-factor*b);
2809 param_matrixWorld.scale(factor,factor);
2811 controlImagePosition();
2814 if (centralWidget->myStatusBar)
2815 centralWidget->displayStatusBar(tr("Zoom: %1%").arg(param_matrixWorld.m11()*100),1000);
2817 if (param_matrixWorld.m11()>1)
2818 setCursor(Qt::OpenHandCursor);
2824 //up, down, dclick, move
2825 void DefaultViewPort::icvmouseHandler(QMouseEvent *evnt, type_mouse_event category, int &cv_event, int &flags)
2827 Qt::KeyboardModifiers modifiers = evnt->modifiers();
2828 Qt::MouseButtons buttons = evnt->buttons();
2831 if(modifiers & Qt::ShiftModifier)
2832 flags |= CV_EVENT_FLAG_SHIFTKEY;
2833 if(modifiers & Qt::ControlModifier)
2834 flags |= CV_EVENT_FLAG_CTRLKEY;
2835 if(modifiers & Qt::AltModifier)
2836 flags |= CV_EVENT_FLAG_ALTKEY;
2838 if(buttons & Qt::LeftButton)
2839 flags |= CV_EVENT_FLAG_LBUTTON;
2840 if(buttons & Qt::RightButton)
2841 flags |= CV_EVENT_FLAG_RBUTTON;
2842 if(buttons & Qt::MidButton)
2843 flags |= CV_EVENT_FLAG_MBUTTON;
2845 cv_event = CV_EVENT_MOUSEMOVE;
2846 switch(evnt->button())
2848 case Qt::LeftButton:
2849 cv_event = tableMouseButtons[category][0];
2850 flags |= CV_EVENT_FLAG_LBUTTON;
2852 case Qt::RightButton:
2853 cv_event = tableMouseButtons[category][1];
2854 flags |= CV_EVENT_FLAG_RBUTTON;
2857 cv_event = tableMouseButtons[category][2];
2858 flags |= CV_EVENT_FLAG_MBUTTON;
2865 void DefaultViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
2867 //to convert mouse coordinate
2869 matrixWorld_inv.map(pt.x(),pt.y(),&pfx,&pfy);
2871 mouseCoordinate.rx()=floor(pfx/ratioX);
2872 mouseCoordinate.ry()=floor(pfy/ratioY);
2875 on_mouse( cv_event, mouseCoordinate.x(),
2876 mouseCoordinate.y(), flags, on_mouse_param );
2880 QSize DefaultViewPort::sizeHint() const
2883 return QSize(image2Draw_mat->cols, image2Draw_mat->rows);
2885 return QGraphicsView::sizeHint();
2889 void DefaultViewPort::draw2D(QPainter *painter)
2891 image2Draw_qt = QImage(image2Draw_mat->data.ptr, image2Draw_mat->cols, image2Draw_mat->rows,image2Draw_mat->step,QImage::Format_RGB888);
2892 painter->drawImage(QRect(0,0,viewport()->width(),viewport()->height()), image2Draw_qt, QRect(0,0, image2Draw_qt.width(), image2Draw_qt.height()) );
2895 //only if CV_8UC1 or CV_8UC3
2896 void DefaultViewPort::drawStatusBar()
2898 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2901 if (mouseCoordinate.x()>=0 &&
2902 mouseCoordinate.y()>=0 &&
2903 mouseCoordinate.x()<image2Draw_qt.width() &&
2904 mouseCoordinate.y()<image2Draw_qt.height())
2905 // if (mouseCoordinate.x()>=0 && mouseCoordinate.y()>=0)
2907 QRgb rgbValue = image2Draw_qt.pixel(mouseCoordinate);
2909 if (nbChannelOriginImage==CV_8UC3 )
2911 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2912 .arg(mouseCoordinate.x())
2913 .arg(mouseCoordinate.y())+
2914 tr("<font color='red'>R:%3 </font>").arg(qRed(rgbValue))+//.arg(value.val[0])+
2915 tr("<font color='green'>G:%4 </font>").arg(qGreen(rgbValue))+//.arg(value.val[1])+
2916 tr("<font color='blue'>B:%5</font>").arg(qBlue(rgbValue))//.arg(value.val[2])
2920 if (nbChannelOriginImage==CV_8UC1)
2922 //all the channel have the same value (because of cvconvertimage), so only the r channel is dsplayed
2923 centralWidget->myStatusBar_msg->setText(tr("<font color='black'>(x=%1, y=%2) ~ </font>")
2924 .arg(mouseCoordinate.x())
2925 .arg(mouseCoordinate.y())+
2926 tr("<font color='grey'>L:%3 </font>").arg(qRed(rgbValue))
2932 //accept only CV_8UC1 and CV_8UC8 image for now
2933 void DefaultViewPort::drawImgRegion(QPainter *painter)
2935 if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
2938 double pixel_width = param_matrixWorld.m11()*ratioX;
2939 double pixel_height = param_matrixWorld.m11()*ratioY;
2941 qreal offsetX = param_matrixWorld.dx()/pixel_width;
2942 offsetX = offsetX - floor(offsetX);
2943 qreal offsetY = param_matrixWorld.dy()/pixel_height;
2944 offsetY = offsetY - floor(offsetY);
2946 QSize view = size();
2947 QVarLengthArray<QLineF, 30> linesX;
2948 for (qreal _x = offsetX*pixel_width; _x < view.width(); _x += pixel_width )
2949 linesX.append(QLineF(_x, 0, _x, view.height()));
2951 QVarLengthArray<QLineF, 30> linesY;
2952 for (qreal _y = offsetY*pixel_height; _y < view.height(); _y += pixel_height )
2953 linesY.append(QLineF(0, _y, view.width(), _y));
2956 QFont f = painter->font();
2957 int original_font_size = f.pointSize();
2959 //f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
2960 f.setPixelSize(10+(pixel_height-threshold_zoom_img_region)/5);
2961 painter->setFont(f);
2964 for (int j=-1;j<height()/pixel_height;j++)//-1 because display the pixels top rows left columns
2965 for (int i=-1;i<width()/pixel_width;i++)//-1
2967 // Calculate top left of the pixel's position in the viewport (screen space)
2968 QPointF pos_in_view((i+offsetX)*pixel_width, (j+offsetY)*pixel_height);
2970 // Calculate top left of the pixel's position in the image (image space)
2971 QPointF pos_in_image = matrixWorld_inv.map(pos_in_view);// Top left of pixel in view
2972 pos_in_image.rx() = pos_in_image.x()/ratioX;
2973 pos_in_image.ry() = pos_in_image.y()/ratioY;
2974 QPoint point_in_image(pos_in_image.x() + 0.5f,pos_in_image.y() + 0.5f);// Add 0.5 for rounding
2977 if (image2Draw_qt.valid(point_in_image))
2978 rgbValue = image2Draw_qt.pixel(point_in_image);
2980 rgbValue = qRgb(0,0,0);
2982 if (nbChannelOriginImage==CV_8UC3)
2986 val = tr("%1 %2").arg(point2.x()).arg(point2.y());
2987 painter->setPen(QPen(Qt::black, 1));
2988 painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2),
2989 Qt::AlignCenter, val);
2993 val = tr("%1").arg(qRed(rgbValue));
2994 painter->setPen(QPen(Qt::red, 1));
2995 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height/3),
2996 Qt::AlignCenter, val);
2998 val = tr("%1").arg(qGreen(rgbValue));
2999 painter->setPen(QPen(Qt::green, 1));
3000 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+pixel_height/3,pixel_width,pixel_height/3),
3001 Qt::AlignCenter, val);
3003 val = tr("%1").arg(qBlue(rgbValue));
3004 painter->setPen(QPen(Qt::blue, 1));
3005 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+2*pixel_height/3,pixel_width,pixel_height/3),
3006 Qt::AlignCenter, val);
3010 if (nbChannelOriginImage==CV_8UC1)
3012 QString val = tr("%1").arg(qRed(rgbValue));
3013 painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height),
3014 Qt::AlignCenter, val);
3018 painter->setPen(QPen(Qt::black, 1));
3019 painter->drawLines(linesX.data(), linesX.size());
3020 painter->drawLines(linesY.data(), linesY.size());
3023 f.setPointSize(original_font_size);
3024 painter->setFont(f);
3028 void DefaultViewPort::drawViewOverview(QPainter *painter)
3030 QSize viewSize = size();
3031 viewSize.scale ( 100, 100,Qt::KeepAspectRatio );
3033 const int margin = 5;
3035 //draw the image's location
3036 painter->setBrush(QColor(0, 0, 0, 127));
3037 painter->setPen(Qt::darkGreen);
3038 painter->drawRect(QRect(width()-viewSize.width()-margin, 0,viewSize.width(),viewSize.height()));
3040 //daw the view's location inside the image
3041 qreal ratioSize = 1/param_matrixWorld.m11();
3042 qreal ratioWindow = (qreal)(viewSize.height())/(qreal)(size().height());
3043 painter->setPen(Qt::darkBlue);
3044 painter->drawRect(QRectF(width()-viewSize.width()-positionCorners.left()*ratioSize*ratioWindow-margin,
3045 -positionCorners.top()*ratioSize*ratioWindow,
3046 (viewSize.width()-1)*ratioSize,
3047 (viewSize.height()-1)*ratioSize)
3051 void DefaultViewPort::drawInstructions(QPainter *painter)
3053 QFontMetrics metrics = QFontMetrics(font());
3054 int border = qMax(4, metrics.leading());
3056 QRect qrect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
3057 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3058 painter->setRenderHint(QPainter::TextAntialiasing);
3059 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3060 QColor(0, 0, 0, 127));
3061 painter->setPen(Qt::white);
3062 painter->fillRect(QRect(0, 0, width(), qrect.height() + 2*border),
3063 QColor(0, 0, 0, 127));
3065 painter->drawText((width() - qrect.width())/2, border,
3066 qrect.width(), qrect.height(),
3067 Qt::AlignCenter | Qt::TextWordWrap, infoText);
3071 void DefaultViewPort::setSize(QSize /*size_*/)
3076 //////////////////////////////////////////////////////
3079 #ifdef HAVE_QT_OPENGL
3081 OpenGlViewPort::OpenGlViewPort(QWidget* _parent) : QGLWidget(_parent), size(-1, -1)
3090 OpenGlViewPort::~OpenGlViewPort()
3094 QWidget* OpenGlViewPort::getWidget()
3099 void OpenGlViewPort::setMouseCallBack(CvMouseCallback callback, void* param)
3101 mouseCallback = callback;
3105 void OpenGlViewPort::writeSettings(QSettings& /*settings*/)
3109 void OpenGlViewPort::readSettings(QSettings& /*settings*/)
3113 double OpenGlViewPort::getRatio()
3115 return (double)width() / height();
3118 void OpenGlViewPort::setRatio(int /*flags*/)
3122 void OpenGlViewPort::updateImage(const CvArr* /*arr*/)
3126 void OpenGlViewPort::startDisplayInfo(QString /*text*/, int /*delayms*/)
3130 void OpenGlViewPort::setOpenGlDrawCallback(CvOpenGlDrawCallback callback, void* userdata)
3132 glDrawCallback = callback;
3133 glDrawData = userdata;
3136 void OpenGlViewPort::makeCurrentOpenGlContext()
3141 void OpenGlViewPort::updateGl()
3143 QGLWidget::updateGL();
3146 void OpenGlViewPort::initializeGL()
3148 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
3151 void OpenGlViewPort::resizeGL(int w, int h)
3153 glViewport(0, 0, w, h);
3156 void OpenGlViewPort::paintGL()
3158 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
3161 glDrawCallback(glDrawData);
3164 void OpenGlViewPort::mousePressEvent(QMouseEvent* evnt)
3166 int cv_event = -1, flags = 0;
3167 QPoint pt = evnt->pos();
3169 icvmouseHandler(evnt, mouse_down, cv_event, flags);
3170 icvmouseProcessing(QPointF(pt), cv_event, flags);
3172 QGLWidget::mousePressEvent(evnt);
3176 void OpenGlViewPort::mouseReleaseEvent(QMouseEvent* evnt)
3178 int cv_event = -1, flags = 0;
3179 QPoint pt = evnt->pos();
3181 icvmouseHandler(evnt, mouse_up, cv_event, flags);
3182 icvmouseProcessing(QPointF(pt), cv_event, flags);
3184 QGLWidget::mouseReleaseEvent(evnt);
3188 void OpenGlViewPort::mouseDoubleClickEvent(QMouseEvent* evnt)
3190 int cv_event = -1, flags = 0;
3191 QPoint pt = evnt->pos();
3193 icvmouseHandler(evnt, mouse_dbclick, cv_event, flags);
3194 icvmouseProcessing(QPointF(pt), cv_event, flags);
3196 QGLWidget::mouseDoubleClickEvent(evnt);
3200 void OpenGlViewPort::mouseMoveEvent(QMouseEvent* evnt)
3202 int cv_event = CV_EVENT_MOUSEMOVE, flags = 0;
3203 QPoint pt = evnt->pos();
3205 //icvmouseHandler: pass parameters for cv_event, flags
3206 icvmouseHandler(evnt, mouse_move, cv_event, flags);
3207 icvmouseProcessing(QPointF(pt), cv_event, flags);
3209 QGLWidget::mouseMoveEvent(evnt);
3212 void OpenGlViewPort::icvmouseHandler(QMouseEvent* evnt, type_mouse_event category, int& cv_event, int& flags)
3214 Qt::KeyboardModifiers modifiers = evnt->modifiers();
3215 Qt::MouseButtons buttons = evnt->buttons();
3218 if (modifiers & Qt::ShiftModifier)
3219 flags |= CV_EVENT_FLAG_SHIFTKEY;
3220 if (modifiers & Qt::ControlModifier)
3221 flags |= CV_EVENT_FLAG_CTRLKEY;
3222 if (modifiers & Qt::AltModifier)
3223 flags |= CV_EVENT_FLAG_ALTKEY;
3225 if (buttons & Qt::LeftButton)
3226 flags |= CV_EVENT_FLAG_LBUTTON;
3227 if (buttons & Qt::RightButton)
3228 flags |= CV_EVENT_FLAG_RBUTTON;
3229 if (buttons & Qt::MidButton)
3230 flags |= CV_EVENT_FLAG_MBUTTON;
3232 cv_event = CV_EVENT_MOUSEMOVE;
3233 switch (evnt->button())
3235 case Qt::LeftButton:
3236 cv_event = tableMouseButtons[category][0];
3237 flags |= CV_EVENT_FLAG_LBUTTON;
3240 case Qt::RightButton:
3241 cv_event = tableMouseButtons[category][1];
3242 flags |= CV_EVENT_FLAG_RBUTTON;
3246 cv_event = tableMouseButtons[category][2];
3247 flags |= CV_EVENT_FLAG_MBUTTON;
3256 void OpenGlViewPort::icvmouseProcessing(QPointF pt, int cv_event, int flags)
3259 mouseCallback(cv_event, pt.x(), pt.y(), flags, mouseData);
3263 QSize OpenGlViewPort::sizeHint() const
3265 if (size.width() > 0 && size.height() > 0)
3268 return QGLWidget::sizeHint();
3271 void OpenGlViewPort::setSize(QSize size_)