├── .gitignore ├── assets ├── detect.tflite └── labelmap.txt ├── screenshots ├── App_general.jpg ├── App_conf_tab1.png ├── App_conf_tab2.png └── App_conf_tab3.png ├── qml.qrc ├── qtquickcontrols2.conf ├── README.md ├── cpp ├── colormanager.h ├── get_top_n.h ├── tensorflowthread.h ├── auxutils.h ├── colormanager.cpp ├── tensorflowthread.cpp ├── objectsrecogfilter.h ├── tensorflow.h ├── objectsrecogfilter.cpp ├── auxutils.cpp └── tensorflow.cpp ├── storage.js ├── main.cpp ├── TFLite_Qt_Pi.pro ├── Home.qml ├── main.qml ├── Configuration.qml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.pro.user 2 | *.directory 3 | -------------------------------------------------------------------------------- /assets/detect.tflite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MechatronicsBlog/RaspberryPi_TFLite_Qt/HEAD/assets/detect.tflite -------------------------------------------------------------------------------- /screenshots/App_general.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MechatronicsBlog/RaspberryPi_TFLite_Qt/HEAD/screenshots/App_general.jpg -------------------------------------------------------------------------------- /screenshots/App_conf_tab1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MechatronicsBlog/RaspberryPi_TFLite_Qt/HEAD/screenshots/App_conf_tab1.png -------------------------------------------------------------------------------- /screenshots/App_conf_tab2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MechatronicsBlog/RaspberryPi_TFLite_Qt/HEAD/screenshots/App_conf_tab2.png -------------------------------------------------------------------------------- /screenshots/App_conf_tab3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MechatronicsBlog/RaspberryPi_TFLite_Qt/HEAD/screenshots/App_conf_tab3.png -------------------------------------------------------------------------------- /qml.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | main.qml 4 | Home.qml 5 | Configuration.qml 6 | qtquickcontrols2.conf 7 | storage.js 8 | 9 | 10 | -------------------------------------------------------------------------------- /qtquickcontrols2.conf: -------------------------------------------------------------------------------- 1 | ; This file can be edited to change the style of the application 2 | ; Read "Qt Quick Controls 2 Configuration File" for details: 3 | ; http://doc.qt.io/qt-5/qtquickcontrols2-configuration.html 4 | 5 | [Controls] 6 | Style=Default 7 | 8 | ;[Controls] 9 | ;Style=Material 10 | 11 | ;[Universal] 12 | ;Theme=System 13 | ;Accent=Red 14 | 15 | ;[Material] 16 | ;Theme=Light 17 | ;Accent=Teal 18 | ;Primary=BlueGrey 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Raspberry Pi - TensorFlow Lite - Qt/QML 2 | 3 | A tutorial to integrate TensorFlow Lite with Qt/QML on Raspberry Pi with an open-source example app for on-device object detection. 4 | 5 | Tutorial: https://mechatronicsblog.com/raspberry-pi,-tensorflow-lite-and-qt-qml:-object-detection-example/ 6 | 7 | App in action: https://youtu.be/tlCcBHNSkNI 8 | 9 | ![App general view](/screenshots/App_general.jpg) 10 | ![App configuration: Tab 1](/screenshots/App_conf_tab1.png) 11 | ![App configuration: Tab 2](/screenshots/App_conf_tab2.png) 12 | ![App configuration: Tab 3](/screenshots/App_conf_tab3.png) 13 | -------------------------------------------------------------------------------- /cpp/colormanager.h: -------------------------------------------------------------------------------- 1 | #ifndef COLORMANAGER_H 2 | #define COLORMANAGER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | class ColorManager 11 | { 12 | public: 13 | QColor getColor(QString element); 14 | static QImage billinearInterpolation(QImage mask, double newHeight, double newWidth); 15 | static QImage applyTransformation(QImage image, QTransform painterTransform); 16 | bool getRgb() const; 17 | void setRgb(bool value); 18 | 19 | private: 20 | QStringList elements; 21 | QList colors; 22 | QColor getNewColor(); 23 | bool rgb = true; 24 | 25 | // NOTE: change or add new colors 26 | const QList defColors = {"#f6a625","#99ca53","#2097d2","#b5563d","#7264d6"}; 27 | }; 28 | 29 | #endif // COLORMANAGER_H 30 | -------------------------------------------------------------------------------- /assets/labelmap.txt: -------------------------------------------------------------------------------- 1 | ??? 2 | person 3 | bicycle 4 | car 5 | motorcycle 6 | airplane 7 | bus 8 | train 9 | truck 10 | boat 11 | traffic light 12 | fire hydrant 13 | ??? 14 | stop sign 15 | parking meter 16 | bench 17 | bird 18 | cat 19 | dog 20 | horse 21 | sheep 22 | cow 23 | elephant 24 | bear 25 | zebra 26 | giraffe 27 | ??? 28 | backpack 29 | umbrella 30 | ??? 31 | ??? 32 | handbag 33 | tie 34 | suitcase 35 | frisbee 36 | skis 37 | snowboard 38 | sports ball 39 | kite 40 | baseball bat 41 | baseball glove 42 | skateboard 43 | surfboard 44 | tennis racket 45 | bottle 46 | ??? 47 | wine glass 48 | cup 49 | fork 50 | knife 51 | spoon 52 | bowl 53 | banana 54 | apple 55 | sandwich 56 | orange 57 | broccoli 58 | carrot 59 | hot dog 60 | pizza 61 | donut 62 | cake 63 | chair 64 | couch 65 | potted plant 66 | bed 67 | ??? 68 | dining table 69 | ??? 70 | ??? 71 | toilet 72 | ??? 73 | tv 74 | laptop 75 | mouse 76 | remote 77 | keyboard 78 | cell phone 79 | microwave 80 | oven 81 | toaster 82 | sink 83 | refrigerator 84 | ??? 85 | book 86 | clock 87 | vase 88 | scissors 89 | teddy bear 90 | hair drier 91 | toothbrush 92 | -------------------------------------------------------------------------------- /storage.js: -------------------------------------------------------------------------------- 1 | function getDatabase() { 2 | return LocalStorage.openDatabaseSync("HelioPi", "0.1", "SettingsDatabase", 100); 3 | } 4 | 5 | function set(setting, value) { 6 | var db = getDatabase(); 7 | var res = ""; 8 | db.transaction(function(tx) { 9 | tx.executeSql('CREATE TABLE IF NOT EXISTS settings(setting TEXT UNIQUE, value TEXT)'); 10 | var rs = tx.executeSql('INSERT OR REPLACE INTO settings VALUES (?,?);', [setting,value]); 11 | if (rs.rowsAffected > 0) { 12 | res = "OK"; 13 | } else { 14 | res = "Error"; 15 | } 16 | } 17 | ); 18 | return res; 19 | } 20 | 21 | function get(setting, default_value) { 22 | var db = getDatabase(); 23 | var res=""; 24 | try { 25 | db.transaction(function(tx) { 26 | var rs = tx.executeSql('SELECT value FROM settings WHERE setting=?;', [setting]); 27 | if (rs.rows.length > 0) { 28 | res = rs.rows.item(0).value; 29 | } else { 30 | res = default_value; 31 | } 32 | }) 33 | } catch (err) { 34 | //console.log("Database " + err); 35 | res = default_value; 36 | }; 37 | return res 38 | } 39 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #include "tensorflow.h" 10 | #include "auxutils.h" 11 | #include "objectsrecogfilter.h" 12 | 13 | double AuxUtils::angleHor = 0; 14 | double AuxUtils::angleVer = 0; 15 | int AuxUtils::width = 0; 16 | int AuxUtils::height = 0; 17 | 18 | using namespace tflite; 19 | 20 | int main(int argc, char *argv[]) 21 | { 22 | QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); 23 | 24 | QGuiApplication app(argc, argv); 25 | app.setOrganizationName("Mechatronics Blog"); 26 | app.setOrganizationDomain("mechatronicsblog.com"); 27 | app.setApplicationName("TFLite_Qt_Pi"); 28 | 29 | QQmlApplicationEngine engine; 30 | 31 | // Register C++ QML types 32 | qmlRegisterType("TensorFlow", 1, 0, "TensorFlow"); 33 | qmlRegisterType("ObjectsRecognizer", 1, 0, "ObjectsRecognizer"); 34 | qmlRegisterType("AuxUtils", 1, 0, "AuxUtils"); 35 | 36 | // Global objects 37 | AuxUtils* auxUtils = new AuxUtils(); 38 | engine.rootContext()->setContextProperty("auxUtils",auxUtils); 39 | engine.rootContext()->setContextProperty("globalEngine",&engine); 40 | 41 | // Register meta types 42 | qRegisterMetaType>("QList"); 43 | qRegisterMetaType>("QList"); 44 | 45 | engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); 46 | if (engine.rootObjects().isEmpty()) 47 | return -1; 48 | 49 | return app.exec(); 50 | } 51 | -------------------------------------------------------------------------------- /cpp/get_top_n.h: -------------------------------------------------------------------------------- 1 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | ==============================================================================*/ 15 | 16 | #ifndef TENSORFLOW_CONTRIB_LITE_EXAMPLES_LABEL_IMAGE_GET_TOP_N_H 17 | #define TENSORFLOW_CONTRIB_LITE_EXAMPLES_LABEL_IMAGE_GET_TOP_N_H 18 | 19 | #include "tensorflow/lite/examples/label_image/get_top_n_impl.h" 20 | 21 | namespace tflite { 22 | namespace label_image { 23 | 24 | template 25 | void get_top_n(T* prediction, int prediction_size, size_t num_results, 26 | float threshold, std::vector>* top_results, 27 | bool input_floating); 28 | 29 | // explicit instantiation so that we can use them otherwhere 30 | template void get_top_n(uint8_t*, int, size_t, float, 31 | std::vector>*, bool); 32 | template void get_top_n(float*, int, size_t, float, 33 | std::vector>*, bool); 34 | 35 | } // namespace label_image 36 | } // namespace tflite 37 | 38 | #endif // TENSORFLOW_CONTRIB_LITE_EXAMPLES_LABEL_IMAGE_GET_TOP_N_H 39 | -------------------------------------------------------------------------------- /cpp/tensorflowthread.h: -------------------------------------------------------------------------------- 1 | #ifndef TENSORFLOWTHREAD_H 2 | #define TENSORFLOWTHREAD_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "tensorflow.h" 10 | 11 | class WorkerTF: public QObject 12 | { 13 | Q_OBJECT 14 | 15 | QImage imgTF; 16 | TensorFlow *tf; 17 | QString source; 18 | QString destination; 19 | bool videoMode; 20 | QMap activeLabels; 21 | bool showAim; 22 | bool showInfTime; 23 | 24 | public: 25 | void setImgTF(const QImage &value); 26 | void setTf(TensorFlow *value); 27 | void setVideoInfo(QString s, QString d, bool sAim, bool sInfTime, QMap aLabels); 28 | 29 | public slots: 30 | void work(); 31 | 32 | private: 33 | QImage processImage(QImage img); 34 | 35 | signals: 36 | void results(int network, QStringList captions, QList confidences, QList boxes, QList masks, int infTime); 37 | void finished(); 38 | void numFrame(int n); 39 | void numFrames(int n); 40 | }; 41 | 42 | class TensorFlowThread: public QObject 43 | { 44 | Q_OBJECT 45 | 46 | public: 47 | TensorFlowThread(); 48 | void setTf(TensorFlow *value); 49 | 50 | void run(QImage imgTF); 51 | void run(QString source, QString destination, bool showAim, bool showInfTime, QMap activeLabels); 52 | 53 | signals: 54 | void results(int network, QStringList captions, QList confidences, QList boxes, QList masks, int infTime); 55 | void numFrame(int n); 56 | void numFrames(int n); 57 | 58 | public slots: 59 | void propagateResults(int network, QStringList captions, QList confidences, QList boxes, QList masks, int infTime); 60 | void propagateNumFrame(int n); 61 | void propagateNumFrames(int n); 62 | 63 | private: 64 | QThread threadTF; 65 | WorkerTF worker; 66 | }; 67 | 68 | #endif // TENSORFLOWTHREAD_H 69 | -------------------------------------------------------------------------------- /TFLite_Qt_Pi.pro: -------------------------------------------------------------------------------- 1 | QT += quick multimedia sensors multimedia-private 2 | CONFIG += console c++11 qml_debug 3 | 4 | # The following define makes your compiler emit warnings if you use 5 | # any feature of Qt which as been marked deprecated (the exact warnings 6 | # depend on your compiler). Please consult the documentation of the 7 | # deprecated API in order to know how to port your code away from it. 8 | DEFINES += QT_DEPRECATED_WARNINGS 9 | 10 | # You can also make your code fail to compile if you use deprecated APIs. 11 | # In order to do so, uncomment the following line. 12 | # You can also select to disable deprecated APIs only up to a certain version of Qt. 13 | #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 14 | 15 | RESOURCES += qml.qrc 16 | 17 | # Additional import path used to resolve QML modules in Qt Creator's code model 18 | QML_IMPORT_PATH = 19 | 20 | # Additional import path used to resolve QML modules just for Qt Quick Designer 21 | QML_DESIGNER_IMPORT_PATH = 22 | 23 | INCLUDEPATH += $$PWD/cpp \ 24 | $$PWD/../tensorflow \ 25 | $$PWD/../tensorflow/tensorflow/lite/tools/make/downloads/flatbuffers/include 26 | 27 | # We consider Linux and distinguish between Raspbian (for Raspberry Pi) and other Linux distributions 28 | linux{ 29 | contains(QMAKE_CXX, .*raspbian.*arm.*):{ 30 | # TensorFlow Lite lib path 31 | LIBS += -L$$PWD/../tensorflow/tensorflow/lite/tools/make/gen/rpi_armv7l/lib 32 | 33 | # Assets to be deployed: path and files 34 | assets.path = /home/pi/qt_apps/$${TARGET}/bin/assets 35 | assets.files = assets/* 36 | } 37 | else { 38 | # TensorFlow Lite lib path 39 | LIBS += -L$$PWD/../tensorflow/tensorflow/lite/tools/make/gen/linux_x86_64/lib 40 | 41 | # Assets to be deployed: path and files 42 | # WARNING: Define yourself the path! 43 | # assets.path = /home/user/app 44 | assets.files = assets/* 45 | } 46 | } 47 | 48 | LIBS += -ltensorflow-lite -ldl 49 | 50 | # Default rules for deployment. 51 | qnx: target.path = /tmp/$${TARGET}/bin 52 | else: unix:!android: target.path = /home/pi/qt_apps/$${TARGET}/bin 53 | !isEmpty(target.path): INSTALLS += target 54 | INSTALLS += assets 55 | 56 | HEADERS += \ 57 | cpp/objectsrecogfilter.h \ 58 | cpp/tensorflow.h \ 59 | cpp/tensorflowthread.h \ 60 | cpp/colormanager.h \ 61 | cpp/get_top_n.h \ 62 | cpp/auxutils.h 63 | 64 | SOURCES += \ 65 | main.cpp \ 66 | cpp/objectsrecogfilter.cpp \ 67 | cpp/tensorflow.cpp \ 68 | cpp/tensorflowthread.cpp \ 69 | cpp/colormanager.cpp \ 70 | cpp/auxutils.cpp 71 | 72 | DISTFILES += \ 73 | Home.qml \ 74 | Configuration.qml \ 75 | main.qml 76 | -------------------------------------------------------------------------------- /cpp/auxutils.h: -------------------------------------------------------------------------------- 1 | #ifndef UTILS_H 2 | #define UTILS_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | const QString assetsPath = "./assets"; 13 | const QString modelName = "detect.tflite"; 14 | const QString labelsName = "labelmap.txt"; 15 | const QString RES_CHAR = "x"; 16 | 17 | class AuxUtils : public QObject 18 | { 19 | Q_OBJECT 20 | 21 | public slots: 22 | static QImage drawText(QImage image, QRectF rect, QString text, Qt::AlignmentFlag pos = Qt::AlignBottom, 23 | Qt::GlobalColor borderColor = Qt::black, 24 | double borderSize = 0.5, 25 | Qt::GlobalColor fontColor = Qt::white, 26 | QFont font = QFont("Times", 16, QFont::Bold)); 27 | static QImage drawBoxes(QImage image, QRect rect, QStringList captions, QList confidences, QList boxes, double minConfidence, 28 | QMap activeLabels, bool rgb); 29 | static QImage drawMasks(QImage image, QRect rect, QStringList captions, QList confidences, QList boxes, QList masks, double minConfidence, QMap activeLabels); 30 | static QString getDefaultModelFilename(); 31 | static QString getDefaultLabelsFilename(); 32 | static QRectF frameMatchImg(QImage img, QSize rectSize); 33 | static int sp(int pixel, QSizeF size); 34 | static double dpi(QSizeF size); 35 | static QString deviceInfo(); 36 | static QString qtVersion(); 37 | static QString getAssetsPath(); 38 | static QImage setOpacity(QImage& image, qreal opacity); 39 | static bool isBGRvideoFrame(QVideoFrame f); 40 | static bool isBGRimage(QImage i); 41 | bool readLabels(QString filename); 42 | QStringList getLabels(); 43 | int numberThreads(); 44 | static QVariantList networkInterfaces(); 45 | static void setAngleHor(double angle); 46 | static void setAngleVer(double angle); 47 | static bool setResolution(QString res); 48 | 49 | signals: 50 | void imageSaved(QString file); 51 | 52 | private: 53 | static QString copyIfNotExistOrUpdate(QString file, QString defFile); 54 | static QByteArray fileMD5(QString filename); 55 | 56 | // Constant values 57 | static constexpr int FONT_PIXEL_SIZE_TEXT = 38; 58 | static constexpr int FONT_PIXEL_SIZE_BOX = 24; 59 | static constexpr double MASK_OPACITY = 0.6; 60 | static constexpr double LINE_WIDTH = 2; 61 | static constexpr int FONT_HEIGHT_MARGIN = 3; 62 | static constexpr int FONT_WIDTH_MARGIN = 6; 63 | QStringList labels; 64 | 65 | public: 66 | static double angleHor; 67 | static double angleVer; 68 | static int width; 69 | static int height; 70 | 71 | }; 72 | 73 | #endif // UTILS_H 74 | -------------------------------------------------------------------------------- /cpp/colormanager.cpp: -------------------------------------------------------------------------------- 1 | #include "colormanager.h" 2 | 3 | #include 4 | 5 | QColor ColorManager::getColor(QString element) 6 | { 7 | int index = elements.indexOf(element); 8 | 9 | if (index>=0) return colors.at(index); 10 | 11 | QColor newColor = getNewColor(); 12 | elements.append(element); 13 | colors.append(newColor); 14 | return newColor; 15 | } 16 | 17 | QColor ColorManager::getNewColor() 18 | { 19 | QColor color = defColors.at(elements.count()%defColors.count()).toRgb(); 20 | 21 | if (!rgb) 22 | { 23 | int r = color.red(); 24 | int b = color.blue(); 25 | 26 | color.setRed(b); 27 | color.setBlue(r); 28 | } 29 | 30 | return color; 31 | } 32 | 33 | bool ColorManager::getRgb() const 34 | { 35 | return rgb; 36 | } 37 | 38 | void ColorManager::setRgb(bool value) 39 | { 40 | rgb = value; 41 | } 42 | 43 | int getColor(QImage mask, QColor color, int x, int y) 44 | { 45 | return color == Qt::red ? qRed(mask.pixel(x,y)) : 46 | color == Qt::blue ? qBlue(mask.pixel(x,y)) : 47 | qGreen(mask.pixel(x,y)); 48 | } 49 | 50 | int billinerColor(QImage mask, QColor color, int xa, int xb, int xc, int xd, int ya, int yb, int yc, int yd, double alpha, double beta) 51 | { 52 | int pa,pb,pc,pd; 53 | 54 | pa = getColor(mask,color,xa,ya); 55 | pb = getColor(mask,color,xb,yb); 56 | pc = getColor(mask,color,xc,yc); 57 | pd = getColor(mask,color,xd,yd); 58 | return (1-alpha)*(1-beta)*pa+alpha*(1-beta)*pb+ 59 | (1-alpha)*beta*pc + alpha*beta*pd + 0.5; 60 | } 61 | 62 | uint billinearPixel(QImage mask, double sx, double sy, int k, int j) 63 | { 64 | double alpha,beta; 65 | int xa,xb,xc,xd,ya,yb,yc,yd; 66 | 67 | xa = k/sx; ya = j/sy; 68 | xb = xa+1; yb = ya; 69 | xc = xa; yc = ya+1; 70 | xd = xa+1; yd = ya+1; 71 | if (xb>=mask.width()) xb--; 72 | if (xd>=mask.width()) xd--; 73 | if (yc>=mask.height()) yc--; 74 | if (yd>=mask.height()) yd--; 75 | alpha = k/sx - xa; 76 | beta = j/sy - ya; 77 | 78 | int red = billinerColor(mask,Qt::red,xa,xb,xc,xd,ya,yb,yc,yd,alpha,beta); 79 | int green = billinerColor(mask,Qt::green,xa,xb,xc,xd,ya,yb,yc,yd,alpha,beta); 80 | int blue = billinerColor(mask,Qt::blue,xa,xb,xc,xd,ya,yb,yc,yd,alpha,beta); 81 | 82 | return qRgb(red,green,blue); 83 | } 84 | 85 | QImage ColorManager::billinearInterpolation(QImage mask, double newHeight, double newWidth) 86 | { 87 | const double sy = newHeight/mask.height(); 88 | const double sx = newWidth/mask.width(); 89 | 90 | // Resize mask to box size 91 | QImage maskScaled(mask.width()*sx,mask.height()*sy,QImage::Format_ARGB32_Premultiplied); 92 | maskScaled.fill(Qt::transparent); 93 | 94 | // Billinear interpolation 95 | // https://chu24688.tian.yam.com/posts/44797337 96 | for(int j=0;j0 33 | viewfinder.resolution: resolution 34 | 35 | onCameraStateChanged: { 36 | if (camera.cameraState === 2) 37 | { 38 | var res = camera.supportedViewfinderResolutions() 39 | 40 | if (res.length>0) 41 | { 42 | resolutions = [] 43 | 44 | for(var i=0; i aLabels) 16 | { 17 | source = s; 18 | destination = d; 19 | showAim = sAim; 20 | showInfTime = sInfTime; 21 | activeLabels = aLabels; 22 | videoMode = true; 23 | } 24 | 25 | void WorkerTF::work() 26 | { 27 | if (!videoMode) 28 | { 29 | tf->run(imgTF); 30 | emit finished(); 31 | emit results(tf->getKindNetwork(),tf->getResults(),tf->getConfidence(),tf->getBoxes(),tf->getMasks(),tf->getInferenceTime()); 32 | } 33 | } 34 | 35 | QImage WorkerTF::processImage(QImage img) 36 | { 37 | // Data 38 | double minConf = tf->getThreshold(); 39 | int inferenceTime = tf->getInferenceTime(); 40 | QStringList results = tf->getResults(); 41 | QList confidence = tf->getConfidence(); 42 | QList boxes = tf->getBoxes(); 43 | QList masks = tf->getMasks(); 44 | 45 | // Draw masks on image 46 | if (!masks.isEmpty()) 47 | img = AuxUtils::drawMasks(img,img.rect(),results,confidence,boxes,masks,minConf,activeLabels); 48 | 49 | // Draw boxes on image 50 | img = AuxUtils::drawBoxes(img,img.rect(),results,confidence,boxes,minConf,activeLabels,true); 51 | 52 | // Show inference time 53 | if (showInfTime) 54 | { 55 | QString text = QString::number(inferenceTime) + " ms"; 56 | img = AuxUtils::drawText(img,img.rect(),text); 57 | } 58 | 59 | return img; 60 | } 61 | 62 | TensorFlowThread::TensorFlowThread() 63 | { 64 | threadTF.setObjectName("TensorFlow thread"); 65 | worker.moveToThread(&threadTF); 66 | QObject::connect(&worker, SIGNAL(results(int, QStringList, QList, QList, QList, int)), this, SLOT(propagateResults(int, QStringList, QList, QList, QList, int))); 67 | QObject::connect(&worker, SIGNAL(numFrame(int)), this, SLOT(propagateNumFrame(int))); 68 | QObject::connect(&worker, SIGNAL(numFrames(int)), this, SLOT(propagateNumFrames(int))); 69 | QObject::connect(&worker, SIGNAL(finished()), &threadTF, SLOT(quit())); 70 | QObject::connect(&threadTF, SIGNAL(started()), &worker, SLOT(work())); 71 | } 72 | 73 | void TensorFlowThread::setTf(TensorFlow *value) 74 | { 75 | worker.setTf(value); 76 | } 77 | 78 | void TensorFlowThread::run(QImage imgTF) 79 | { 80 | worker.setImgTF(imgTF); 81 | threadTF.start(); 82 | } 83 | 84 | void TensorFlowThread::run(QString source, QString destination, bool showAim, bool showInfTime, QMap activeLabels) 85 | { 86 | worker.setVideoInfo(source,destination,showAim,showInfTime,activeLabels); 87 | threadTF.start(); 88 | } 89 | 90 | void TensorFlowThread::propagateResults(int network, QStringList captions, QList confidences, QList boxes, QList masks, int infTime) 91 | { 92 | emit results(network,captions,confidences,boxes,masks,infTime); 93 | } 94 | 95 | void TensorFlowThread::propagateNumFrame(int n) 96 | { 97 | emit numFrame(n); 98 | } 99 | 100 | void TensorFlowThread::propagateNumFrames(int n) 101 | { 102 | emit numFrames(n); 103 | } 104 | -------------------------------------------------------------------------------- /cpp/objectsrecogfilter.h: -------------------------------------------------------------------------------- 1 | #ifndef OBJECTSRECOGFILTER_H 2 | #define OBJECTSRECOGFILTER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "tensorflow.h" 11 | #include "tensorflowthread.h" 12 | 13 | // https://stackoverflow.com/questions/43106069/how-to-convert-qvideoframe-with-yuv-data-to-qvideoframe-with-rgba32-data-in 14 | 15 | class ObjectsRecogFilterRunable; 16 | 17 | class ObjectsRecogFilter : public QAbstractVideoFilter 18 | { 19 | Q_OBJECT 20 | 21 | Q_PROPERTY(double cameraOrientation READ getCameraOrientation WRITE setCameraOrientation) 22 | Q_PROPERTY(double videoOrientation READ getVideoOrientation WRITE setVideoOrientation) 23 | Q_PROPERTY(double minConfidence READ getMinConfidence WRITE setMinConfidence) 24 | Q_PROPERTY(QSize contentSize READ getContentSize WRITE setContentSize) 25 | Q_PROPERTY(bool acceleration READ getAcceleration WRITE setAcceleration) 26 | Q_PROPERTY(int nThreads READ getNThreads WRITE setNThreads) 27 | Q_PROPERTY(bool showInfTime READ getShowInfTime WRITE setShowInfTime) 28 | Q_PROPERTY(double angle READ getAngle NOTIFY angleChanged) 29 | 30 | public slots: 31 | void init(int imgHeight, int imgWidth); 32 | void initInput(int imgHeight, int imgWidth); 33 | QMap getActiveLabels(); 34 | bool getActiveLabel(QString key); 35 | void setActiveLabel(QString key, bool value); 36 | 37 | public: 38 | ObjectsRecogFilter(); 39 | QVideoFilterRunnable *createFilterRunnable(); 40 | void setCameraOrientation(double o); 41 | void setVideoOrientation(double o); 42 | double getCameraOrientation(); 43 | double getVideoOrientation(); 44 | double getMinConfidence() const; 45 | void setMinConfidence(double value); 46 | bool getRunning(); 47 | void releaseRunning(); 48 | QSize getContentSize() const; 49 | void setContentSize(const QSize &value); 50 | bool getAcceleration() const; 51 | void setAcceleration(bool value); 52 | int getNThreads() const; 53 | void setNThreads(int value); 54 | bool getShowInfTime() const; 55 | void setShowInfTime(bool value); 56 | void setFrameSize(QSize size); 57 | void setFrameRate(int fps); 58 | double getAngle() const; 59 | void setAngle(const double value); 60 | double getImgHeight(); 61 | double getImgWidth(); 62 | bool getInitialized() const; 63 | void setInitialized(bool value); 64 | 65 | private: 66 | ObjectsRecogFilterRunable *rfr; 67 | TensorFlow tf; 68 | TensorFlowThread tft; 69 | double camOrientation; 70 | double vidOrientation; 71 | double minConf; 72 | bool acc; 73 | int nThr; 74 | bool infTime; 75 | QMutex mutex; 76 | bool running; 77 | QSize videoSize; 78 | QMap activeLabels; 79 | void setRunning(bool val); 80 | double ang; 81 | bool initialized; 82 | 83 | signals: 84 | void runTensorFlow(QImage imgTF); 85 | void focusDataChanged(); 86 | void focusedChanged(); 87 | void angleChanged(); 88 | void errorXChanged(); 89 | void errorYChanged(); 90 | 91 | private slots: 92 | void TensorFlowExecution(QImage imgTF); 93 | void processResults(int network, QStringList res, QList conf, QList boxes, QList masks, int inftime); 94 | }; 95 | 96 | class ObjectsRecogFilterRunable : public QVideoFilterRunnable 97 | { 98 | public: 99 | ObjectsRecogFilterRunable(ObjectsRecogFilter *filter, QStringList res); 100 | QVideoFrame run(QVideoFrame *input, const QVideoSurfaceFormat &surfaceFormat, RunFlags flags); 101 | void setResults(int net, QStringList res, QList conf, QList box, QList mask, int inftime); 102 | 103 | private: 104 | ObjectsRecogFilter *m_filter; 105 | int network; 106 | QStringList results; 107 | QList confidence; 108 | QList boxes; 109 | QList masks; 110 | int inferenceTime; 111 | QElapsedTimer timer; 112 | 113 | }; 114 | 115 | #endif // OBJECTSRECOGFILTER_H 116 | -------------------------------------------------------------------------------- /cpp/tensorflow.h: -------------------------------------------------------------------------------- 1 | #ifndef TENSORFLOW_H 2 | #define TENSORFLOW_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "tensorflow/lite/error_reporter.h" 9 | #include "tensorflow/lite/interpreter.h" 10 | #include "tensorflow/lite/model.h" 11 | #include "tensorflow/lite/graph_info.h" 12 | #include "tensorflow/lite/kernels/register.h" 13 | 14 | using namespace tflite; 15 | 16 | class TensorFlow : public QObject 17 | { 18 | Q_OBJECT 19 | public: 20 | explicit TensorFlow(QObject *parent = nullptr); 21 | ~TensorFlow(); 22 | 23 | static const int knIMAGE_CLASSIFIER = 1; 24 | static const int knOBJECT_DETECTION = 2; 25 | static const int DEF_BOX_DISTANCE = 10; 26 | 27 | signals: 28 | 29 | public slots: 30 | bool init(int imgHeight, int imgWidth); 31 | bool run(QImage img); 32 | QString getFilename() const; 33 | void setFilename(const QString &value); 34 | QString getLabelsFilename() const; 35 | void setLabelsFilename(const QString &value); 36 | bool getAccelaration() const; 37 | void setAccelaration(bool value); 38 | bool getVerbose() const; 39 | void setVerbose(bool value); 40 | int getNumThreads() const; 41 | void setNumThreads(int value); 42 | int getHeight() const; 43 | int getWidth() const; 44 | int getChannels() const; 45 | QString getLabel(int index); 46 | QString getResultCaption(int index); 47 | double getResultConfidence(int index); 48 | QStringList getResults(); 49 | QList getConfidence(); 50 | QList getBoxes(); 51 | QList getMasks(); 52 | int getInferenceTime(); 53 | int getKindNetwork(); 54 | double getThreshold() const; 55 | void setThreshold(double value); 56 | void initInput(int imgHeight, int imgWidth); 57 | bool initTFLite(int imgHeight, int imgWidth); 58 | bool setInputsTFLite(QImage image); 59 | bool inferenceTFLite(); 60 | bool getClassfierOutputsTFLite(std::vector> *top_results); 61 | bool getObjectOutputsTFLite(QStringList &captions, QList &confidences, QList &locations, QList &masks); 62 | 63 | private: 64 | // Configuration constants 65 | const double MASK_THRESHOLD = 0.3; 66 | 67 | // Output names 68 | const QString num_detections = "num_detections"; 69 | const QString detection_classes = "detection_classes"; 70 | const QString detection_scores = "detection_scores"; 71 | const QString detection_boxes = "detection_boxes"; 72 | const QString detection_masks = "detection_masks"; 73 | 74 | // Network configuration 75 | bool has_detection_masks; 76 | 77 | // Threshold 78 | double threshold; 79 | 80 | // Image properties 81 | const QImage::Format format = QImage::Format_RGB888; 82 | const int numChannels = 3; 83 | 84 | // Kind of network in model 85 | int kind_network; 86 | 87 | // Model filename 88 | QString filename; 89 | 90 | // Labels & box priors filename & data 91 | QString labelsFilename; 92 | QStringList labels; 93 | 94 | // Results 95 | QStringList rCaption; 96 | QList rConfidence; 97 | QList rBox; 98 | QList rMasks; 99 | int inferenceTime; 100 | 101 | // Initialized 102 | bool initialized; 103 | 104 | // Accelaration 105 | bool accelaration; 106 | 107 | // Verbose 108 | bool verbose; 109 | 110 | // Number of threads 111 | int numThreads; 112 | 113 | // Image configuration 114 | int wanted_height, wanted_width, wanted_channels; 115 | int img_height, img_width, img_channels; 116 | 117 | // Model 118 | std::unique_ptr model; 119 | // Resolver 120 | tflite::ops::builtin::BuiltinOpResolver resolver; 121 | // Interpreter 122 | std::unique_ptr interpreter; 123 | // Error reporter 124 | StderrReporter error_reporter; 125 | // Outputs 126 | std::vector outputs; 127 | 128 | // Private functions 129 | bool readLabels(); 130 | bool setInputs(QImage image); 131 | bool inference(); 132 | bool getClassfierOutputs(std::vector> *top_results); 133 | bool getObjectOutputs(QStringList &captions, QList &confidences, QList &locations, QList &images); 134 | }; 135 | 136 | #endif // TENSORFLOW_H 137 | -------------------------------------------------------------------------------- /main.qml: -------------------------------------------------------------------------------- 1 | import QtQuick 2.9 2 | import QtQuick.Controls 2.2 3 | import QtQuick.LocalStorage 2.0 4 | import "storage.js" as Settings 5 | 6 | ApplicationWindow { 7 | id: window 8 | visible: true 9 | title: qsTr("TensorFlow Lite & Qt") 10 | 11 | readonly property string tMinConfidence: 'minConfidence' 12 | readonly property string tNThreads: 'nThreads' 13 | readonly property string tShowInfTime: 'showInfTime' 14 | readonly property string tResolution: 'resolution' 15 | 16 | // Default values 17 | readonly property double defMinConfidence: 0.7 18 | readonly property bool defShowInfTime: false 19 | readonly property int defNumThreads: 1 20 | readonly property bool defTFObject: true 21 | readonly property string defResolution: "640x480" 22 | 23 | property double minConfidence: Settings.get(tMinConfidence,defMinConfidence) 24 | property int nThreads: Settings.get(tNThreads,defNumThreads) 25 | property bool showInfTime: Settings.get(tShowInfTime,defShowInfTime) == 0 ? false : true 26 | property string resolution: Settings.get(tResolution,defResolution) 27 | property var tfObjects: [] 28 | 29 | header: ToolBar { 30 | contentHeight: toolButton.implicitHeight 31 | 32 | ToolButton { 33 | id: toolButton 34 | text: stackView.depth > 1 ? "\u25C0" : "\u2630" 35 | font.pixelSize: Qt.application.font.pixelSize * 1.6 36 | onClicked: { 37 | if (stackView.depth > 1) { 38 | stackView.pop() 39 | } else { 40 | drawer.open() 41 | } 42 | } 43 | } 44 | 45 | Label { 46 | text: stackView.currentItem.title 47 | anchors.centerIn: parent 48 | } 49 | } 50 | 51 | Drawer { 52 | id: drawer 53 | width: window.width * 0.3 54 | height: window.height 55 | 56 | Column { 57 | anchors.fill: parent 58 | 59 | ItemDelegate { 60 | text: qsTr("Settings") 61 | width: parent.width 62 | onClicked: { 63 | stackView.push(configuration) 64 | drawer.close() 65 | } 66 | } 67 | } 68 | } 69 | 70 | StackView { 71 | id: stackView 72 | initialItem: home 73 | anchors.fill: parent 74 | } 75 | 76 | Home{ 77 | id: home 78 | visible: false 79 | minConfidence: window.minConfidence 80 | nThreads: window.nThreads 81 | showInfTime: window.showInfTime 82 | resolution: window.resolution 83 | } 84 | 85 | Configuration{ 86 | id: configuration 87 | visible: false 88 | 89 | minConfidence: window.minConfidence 90 | nThreads: window.nThreads 91 | showInfTime: window.showInfTime 92 | resolution: window.resolution 93 | resolutions: home.resolutions 94 | 95 | onMinConfidenceChanged: {Settings.set(tMinConfidence,minConfidence); window.minConfidence = minConfidence } 96 | onNThreadsChanged: {Settings.set(tNThreads,nThreads); window.nThreads = nThreads } 97 | onShowInfTimeChanged: {Settings.set(tShowInfTime,showInfTime); window.showInfTime = showInfTime } 98 | onResolutionUpdated: {Settings.set(tResolution,resolution); window.resolution = resolution} 99 | 100 | onObjectChanged: { 101 | tfObjects[label] = checked 102 | Settings.set(label,checked) 103 | setActiveLabel(label,checked) 104 | } 105 | } 106 | 107 | Component.onCompleted: init() 108 | 109 | function init() 110 | { 111 | console.log("Initialization") 112 | 113 | var labels = auxUtils.getLabels() 114 | 115 | tfObjects = [] 116 | for(var i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "auxutils.h" 9 | #include "private/qvideoframe_p.h" 10 | 11 | // WARNING: same TensorFlow initialization repeated in ObjectRecogFilter and TensorFlowQML constructors 12 | ObjectsRecogFilter::ObjectsRecogFilter() 13 | { 14 | connect(this, SIGNAL(runTensorFlow(QImage)), this, SLOT(TensorFlowExecution(QImage))); 15 | connect(&tft,SIGNAL(results(int, QStringList, QList, QList, QList, int)),this,SLOT(processResults(int, QStringList, QList, QList, QList, int))); 16 | 17 | tf.setFilename(AuxUtils::getDefaultModelFilename()); 18 | tf.setLabelsFilename(AuxUtils::getDefaultLabelsFilename()); 19 | tf.setAccelaration(true); 20 | tf.setNumThreads(QThread::idealThreadCount()); 21 | 22 | releaseRunning(); 23 | initialized = false; 24 | } 25 | 26 | void ObjectsRecogFilter::init(int imgHeight, int imgWidth) 27 | { 28 | initialized = tf.init(imgHeight,imgWidth); 29 | tft.setTf(&tf); 30 | } 31 | 32 | void ObjectsRecogFilter::initInput(int imgHeight, int imgWidth) 33 | { 34 | tf.initInput(imgHeight,imgWidth); 35 | } 36 | 37 | void ObjectsRecogFilter::TensorFlowExecution(QImage imgTF) 38 | { 39 | tf.setAccelaration(getAcceleration()); 40 | tf.setNumThreads(getNThreads()); 41 | tft.run(imgTF); 42 | } 43 | 44 | void ObjectsRecogFilter::processResults(int network, QStringList res, QList conf, QList boxes, QList masks, int inftime) 45 | { 46 | rfr->setResults(network,res,conf,boxes,masks,inftime); 47 | releaseRunning(); 48 | } 49 | 50 | void ObjectsRecogFilter::setCameraOrientation(double o) 51 | { 52 | camOrientation = o; 53 | } 54 | 55 | void ObjectsRecogFilter::setVideoOrientation(double o) 56 | { 57 | vidOrientation = o; 58 | } 59 | 60 | double ObjectsRecogFilter::getCameraOrientation() 61 | { 62 | return camOrientation; 63 | } 64 | 65 | double ObjectsRecogFilter::getVideoOrientation() 66 | { 67 | return vidOrientation; 68 | } 69 | 70 | bool ObjectsRecogFilter::getRunning() 71 | { 72 | QMutexLocker locker(&mutex); 73 | 74 | bool val = running; 75 | if (!val) setRunning(true); 76 | 77 | return !val; 78 | } 79 | 80 | void ObjectsRecogFilter::setRunning(bool val) 81 | { 82 | running = val; 83 | } 84 | 85 | bool ObjectsRecogFilter::getInitialized() const 86 | { 87 | return initialized; 88 | } 89 | 90 | void ObjectsRecogFilter::setInitialized(bool value) 91 | { 92 | initialized = value; 93 | } 94 | 95 | void ObjectsRecogFilter::releaseRunning() 96 | { 97 | QMutexLocker locker(&mutex); 98 | 99 | setRunning(false); 100 | } 101 | 102 | QSize ObjectsRecogFilter::getContentSize() const 103 | { 104 | return videoSize; 105 | } 106 | 107 | void ObjectsRecogFilter::setContentSize(const QSize &value) 108 | { 109 | videoSize = value; 110 | } 111 | 112 | bool ObjectsRecogFilter::getAcceleration() const 113 | { 114 | return acc; 115 | } 116 | 117 | void ObjectsRecogFilter::setAcceleration(bool value) 118 | { 119 | acc = value; 120 | } 121 | 122 | int ObjectsRecogFilter::getNThreads() const 123 | { 124 | return nThr; 125 | } 126 | 127 | void ObjectsRecogFilter::setNThreads(int value) 128 | { 129 | nThr = value; 130 | } 131 | 132 | bool ObjectsRecogFilter::getShowInfTime() const 133 | { 134 | return infTime; 135 | } 136 | 137 | void ObjectsRecogFilter::setShowInfTime(bool value) 138 | { 139 | infTime = value; 140 | } 141 | 142 | double ObjectsRecogFilter::getMinConfidence() const 143 | { 144 | return minConf; 145 | } 146 | 147 | void ObjectsRecogFilter::setMinConfidence(double value) 148 | { 149 | minConf = value; 150 | tf.setThreshold(minConf); 151 | } 152 | 153 | ObjectsRecogFilterRunable::ObjectsRecogFilterRunable(ObjectsRecogFilter *filter, QStringList res) 154 | { 155 | m_filter = filter; 156 | results = res; 157 | } 158 | 159 | void ObjectsRecogFilterRunable::setResults(int net, QStringList res, QList conf, QList box, QList mask, int inftime) 160 | { 161 | network = net; 162 | results = res; 163 | confidence = conf; 164 | boxes = box; 165 | masks = mask; 166 | inferenceTime = inftime; 167 | } 168 | 169 | void ObjectsRecogFilter::setActiveLabel(QString key, bool value) 170 | { 171 | activeLabels[key] = value; 172 | } 173 | 174 | QMap ObjectsRecogFilter::getActiveLabels() 175 | { 176 | return activeLabels; 177 | } 178 | 179 | bool ObjectsRecogFilter::getActiveLabel(QString key) 180 | { 181 | return activeLabels.value(key,false); 182 | } 183 | 184 | double ObjectsRecogFilter::getAngle() const 185 | { 186 | return ang; 187 | } 188 | 189 | void ObjectsRecogFilter::setAngle(const double value) 190 | { 191 | ang = value; 192 | emit angleChanged(); 193 | } 194 | 195 | double ObjectsRecogFilter::getImgHeight() 196 | { 197 | return tf.getHeight(); 198 | } 199 | 200 | double ObjectsRecogFilter::getImgWidth() 201 | { 202 | return tf.getWidth(); 203 | } 204 | 205 | QImage rotateImage(QImage img, double rotation) 206 | { 207 | QPoint center = img.rect().center(); 208 | QMatrix matrix; 209 | matrix.translate(center.x(), center.y()); 210 | matrix.rotate(rotation); 211 | 212 | return img.transformed(matrix); 213 | } 214 | 215 | QVideoFrame ObjectsRecogFilterRunable::run(QVideoFrame *input, const QVideoSurfaceFormat &surfaceFormat, RunFlags flags) 216 | { 217 | Q_UNUSED(surfaceFormat); 218 | Q_UNUSED(flags); 219 | 220 | QImage img; 221 | bool mirrorHorizontal; 222 | bool mirrorVertical = false; 223 | 224 | if(input->isValid()) 225 | { 226 | // Get image from video frame, we need to convert it 227 | // for unsupported QImage formats, i.e Format_YUV420P 228 | // 229 | // When input has an unsupported format the QImage 230 | // default format is ARGB32 231 | // 232 | // NOTE: BGR images are not properly managed by qt_imageFromVideoFrame 233 | // 234 | bool BGRVideoFrame = AuxUtils::isBGRvideoFrame(*input); 235 | if (BGRVideoFrame) 236 | { 237 | input->map(QAbstractVideoBuffer::ReadOnly); 238 | img = QImage(input->bits(),input->width(),input->height(),QImage::Format_ARGB32).copy(); 239 | input->unmap(); 240 | // WARNING: Mirror only for Android? How to check if this has to be done? 241 | // surfaceFormat.isMirrored() == false for Android 242 | mirrorVertical = true; 243 | } 244 | else img = qt_imageFromVideoFrame(*input); 245 | 246 | // Check if mirroring is needed 247 | if (!mirrorVertical) mirrorVertical = surfaceFormat.isMirrored(); 248 | mirrorHorizontal = surfaceFormat.scanLineDirection() == QVideoSurfaceFormat::BottomToTop; 249 | img = img.mirrored(mirrorHorizontal,mirrorVertical); 250 | 251 | // Check img is valid 252 | if (img.format() != QImage::Format_Invalid) 253 | { 254 | // Take into account the rotation 255 | img = rotateImage(img,-m_filter->getVideoOrientation()); 256 | 257 | // If not initialized, intialize with image size 258 | if (!m_filter->getInitialized()) 259 | m_filter->init(img.height(),img.width()); 260 | else if (m_filter->getImgHeight() != img.height() || 261 | m_filter->getImgWidth() != img.width()) 262 | // If image size changed, initialize input tensor 263 | m_filter->initInput(img.height(),img.width()); 264 | 265 | // Get a mutex for creating a thread to execute TensorFlow 266 | if (m_filter->getRunning()) 267 | { 268 | //img.save("/home/pi/imageTF.png"); 269 | emit m_filter->runTensorFlow(img); 270 | } 271 | 272 | // Image classification network 273 | if (network == TensorFlow::knIMAGE_CLASSIFIER) 274 | { 275 | // Get current TensorFlow outputs 276 | QString objStr = results.count()>0 ? results.first() : ""; 277 | double objCon = confidence.count()>0 ? confidence.first() : -1; 278 | 279 | // Check if there are results, the label is active & the minimum confidence level is reached 280 | if (objStr.length()>0 && objCon >= m_filter->getMinConfidence() && m_filter->getActiveLabel(objStr)) 281 | { 282 | // Formatting of confidence value 283 | QString confVal = QString::number(objCon * 100, 'f', 2) + " %"; 284 | 285 | 286 | // Content size 287 | QRectF srcRect = AuxUtils::frameMatchImg(img,m_filter->getContentSize()); 288 | 289 | // Text 290 | QString text = objStr + '\n' + confVal; 291 | 292 | // Show inference time 293 | if (m_filter->getShowInfTime()) 294 | text = text + '\n' + QString::number(inferenceTime) + " ms"; 295 | 296 | img = AuxUtils::drawText(img,srcRect,text); 297 | } 298 | } 299 | // Object detection network 300 | else if (network == TensorFlow::knOBJECT_DETECTION) 301 | { 302 | QRectF srcRect; 303 | bool showInfTime = m_filter->getShowInfTime(); 304 | 305 | // Calculate source rect if needed 306 | if (showInfTime) 307 | srcRect = AuxUtils::frameMatchImg(img,m_filter->getContentSize()); 308 | 309 | // Draw masks on image 310 | if (!masks.isEmpty()) 311 | img = AuxUtils::drawMasks(img,img.rect(),results,confidence,boxes,masks,m_filter->getMinConfidence(),m_filter->getActiveLabels()); 312 | 313 | // Draw boxes on image 314 | img = AuxUtils::drawBoxes(img,img.rect(),results,confidence,boxes,m_filter->getMinConfidence(), 315 | m_filter->getActiveLabels(),!BGRVideoFrame); 316 | 317 | // Show inference time 318 | if (showInfTime) 319 | { 320 | QString text = QString::number(inferenceTime) + " ms"; 321 | img = AuxUtils::drawText(img,srcRect,text); 322 | } 323 | 324 | } 325 | 326 | // Restore rotation 327 | img = rotateImage(img,m_filter->getVideoOrientation()); 328 | } 329 | 330 | // NOTE: for BGR images loaded as RGB 331 | if (BGRVideoFrame) img = img.rgbSwapped(); 332 | 333 | // Return video frame from img 334 | return QVideoFrame(img); 335 | } 336 | 337 | return *input; 338 | } 339 | 340 | QVideoFilterRunnable *ObjectsRecogFilter::createFilterRunnable() 341 | { 342 | rfr = new ObjectsRecogFilterRunable(this,tf.getResults()); 343 | return rfr; 344 | } 345 | -------------------------------------------------------------------------------- /cpp/auxutils.cpp: -------------------------------------------------------------------------------- 1 | #include "auxutils.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #include "colormanager.h" 20 | #include "math.h" 21 | 22 | double AuxUtils::dpi(QSizeF size) 23 | { 24 | if (QGuiApplication::screens().count() > 0) 25 | { 26 | double dpi = QGuiApplication::screens().first()->logicalDotsPerInch(); 27 | double lx = 1*size.width()/QGuiApplication::screens().first()->size().width(); 28 | double ly = 1*size.height()/QGuiApplication::screens().first()->size().height(); 29 | double ml = 0.5*(lx+ly); 30 | 31 | return dpi * ml; 32 | } 33 | return 160; 34 | } 35 | 36 | // FIXME: properly implement this to be independent of the screen size and resolution 37 | int AuxUtils::sp(int pixel, QSizeF size) 38 | { 39 | //qDebug() << "Physical DPI:" << QApplication::screens().first()->physicalDotsPerInch(); 40 | //qDebug() << "Logical DPI:" << QApplication::screens().first()->logicalDotsPerInch(); 41 | //qDebug() << "Pixel ratio:" << QApplication::screens().first()->devicePixelRatio(); 42 | 43 | // iPhone 7: 1.5 44 | // iPad Mini 4: 1 45 | // Android: 1 46 | // Linux: 4 47 | // iPad Pro: 1 48 | // Raspberry Pi touch screen 7": 1 49 | 50 | return int(pixel * (dpi(size) / 160) * qApp->devicePixelRatio()); 51 | } 52 | 53 | QString AuxUtils::deviceInfo() 54 | { 55 | QSysInfo info; 56 | 57 | return info.prettyProductName() + '\n' + '\n' + 58 | QString::number(QThread::idealThreadCount()) + " " + tr("cores"); 59 | } 60 | 61 | int AuxUtils::numberThreads() 62 | { 63 | return QThread::idealThreadCount(); 64 | } 65 | 66 | QString AuxUtils::qtVersion() 67 | { 68 | return qVersion(); 69 | } 70 | 71 | QString AuxUtils::getAssetsPath() 72 | { 73 | return assetsPath; 74 | } 75 | 76 | QImage AuxUtils::drawText(QImage image, QRectF rect, QString text, Qt::AlignmentFlag pos, Qt::GlobalColor borderColor, double borderSize, Qt::GlobalColor fontColor, QFont font) 77 | { 78 | QPainter p; 79 | QRectF r = rect; 80 | QPainterPath path; 81 | QPen pen; 82 | QBrush brush; 83 | QStringList lines; 84 | 85 | if (p.begin(&image)) 86 | { 87 | // Configure font 88 | font.setPixelSize(AuxUtils::sp(FONT_PIXEL_SIZE_TEXT,rect.size())); 89 | font.setStyleHint(QFont::Times, QFont::PreferAntialias); 90 | 91 | // Configure pen 92 | pen.setWidthF(borderSize); 93 | pen.setStyle(Qt::SolidLine); 94 | pen.setColor(borderColor); 95 | pen.setCapStyle(Qt::RoundCap); 96 | pen.setJoinStyle(Qt::RoundJoin); 97 | 98 | // Configure brush 99 | brush.setStyle(Qt::SolidPattern); 100 | brush.setColor(fontColor); 101 | 102 | // Get lines 103 | lines = text.split('\n',QString::SkipEmptyParts); 104 | 105 | // Calculate text position 106 | QFontMetrics fm(font); 107 | for(int i=0;i confidences, QList boxes, QList masks, 141 | double minConfidence, QMap activeLabels) 142 | { 143 | Q_UNUSED(activeLabels); 144 | Q_UNUSED(captions); 145 | Q_UNUSED(rect); 146 | 147 | QPainter p; 148 | 149 | 150 | if (p.begin(&image)) 151 | { 152 | // http://doc.qt.io/qt-5/qpainter.html#CompositionMode-enum 153 | p.setCompositionMode(QPainter::CompositionMode_SourceOver); 154 | 155 | // Draw each mask 156 | for(int i=0;i= minConfidence && activeLabels[captions[i]]) 160 | { 161 | masks[i] = setOpacity(masks[i],MASK_OPACITY); 162 | p.drawImage(boxes[i].topLeft(),masks[i]); 163 | } 164 | } 165 | } 166 | return image; 167 | } 168 | 169 | QPointF boxCenter(QRectF rect, int offsetX=0, int offsetY=0) 170 | { 171 | return QPointF(rect.left() + rect.width()*0.5 + offsetX, rect.top() + rect.height()*0.5 + offsetY); 172 | } 173 | 174 | QRectF pointCircle(QPointF p, double radius) 175 | { 176 | return QRectF(p.x()-radius,p.y()-radius,2*radius,2*radius); 177 | } 178 | 179 | QRectF pointRect(QPointF p, double width, double height) 180 | { 181 | return QRectF(p.x()-0.5*width,p.y()-0.5*height,width,height); 182 | } 183 | 184 | QPointF midPoint(QPointF a, QPointF b) 185 | { 186 | return QPointF(0.5*(a.x()+b.x()),0.5*(a.y()+b.y())); 187 | } 188 | 189 | bool rectInside(QRectF a, QRectF b) 190 | { 191 | return b.left()>=a.left() && b.top()>=a.top() && b.right()<=a.right() && b.bottom()<=a.bottom(); 192 | } 193 | 194 | bool pointInside(QPointF p, QRectF r) 195 | { 196 | return p.x()>=r.left() && p.x()<=r.right() && p.y()<=r.top() && p.y()>=r.bottom(); 197 | } 198 | 199 | double getAngle(QPointF a, QPointF b) 200 | { 201 | double angle = atan2(a.y()-b.y(),a.x()-b.x()) * 180 / M_PI; 202 | 203 | // Check it is not: Nan, -Inf or +Inf 204 | angle = angle != angle || angle > std::numeric_limits::max() || angle < -std::numeric_limits::max() ? 0 : angle; 205 | 206 | return angle; 207 | } 208 | 209 | QImage AuxUtils::drawBoxes(QImage image, QRect rect, QStringList captions, QList confidences, QList boxes, double minConfidence, 210 | QMap activeLabels, bool rgb) 211 | { 212 | Q_UNUSED(rect); 213 | 214 | ColorManager cm; 215 | QPainter p; 216 | QBrush brush; 217 | QPen pen; 218 | QFont font; 219 | QPen fPen; 220 | QBrush bBrush; 221 | QPen bPen; 222 | 223 | if (p.begin(&image)) 224 | { 225 | // Configure pen 226 | pen.setStyle(Qt::SolidLine); 227 | pen.setWidthF(LINE_WIDTH); 228 | 229 | // Configure font pen 230 | fPen.setStyle(Qt::SolidLine); 231 | fPen.setColor(Qt::black); 232 | 233 | // Configure back pen 234 | bPen.setStyle(Qt::SolidLine); 235 | 236 | // Configure brush 237 | brush.setStyle(Qt::NoBrush); 238 | 239 | // Configure back brush 240 | bBrush.setStyle(Qt::SolidPattern); 241 | 242 | // Configure font 243 | font.setCapitalization(QFont::Capitalize); 244 | font.setPixelSize(AuxUtils::sp(FONT_PIXEL_SIZE_BOX,rect.size())); 245 | 246 | // Configure painter 247 | p.setRenderHint(QPainter::Antialiasing); 248 | p.setFont(font); 249 | 250 | QFontMetrics fm(font); 251 | 252 | // Draw each box 253 | for(int i=0;i= minConfidence && activeLabels[captions[i]]) 257 | { 258 | // Draw box 259 | cm.setRgb(rgb); 260 | pen.setColor(cm.getColor(captions[i])); 261 | p.setPen(pen); 262 | p.setBrush(brush); 263 | p.drawRect(boxes[i]); 264 | 265 | // Format text 266 | QString confVal = QString::number(qRound(confidences[i] * 100)) + " %"; 267 | QString text = captions[i] + " - " + confVal; 268 | 269 | // Text rect 270 | int width = fm.width(text)+FONT_WIDTH_MARGIN; 271 | int height = fm.height(); 272 | int left = boxes[i].left()>=0 ? int(boxes[i].left()) : int(boxes[i].right()-width); 273 | int top = boxes[i].top()-fm.height()>=0 ? int(boxes[i].top()-fm.height()) : int(boxes[i].bottom()); 274 | 275 | // Text position 276 | int tLeft = left+FONT_WIDTH_MARGIN/2; 277 | int tTop = boxes[i].top()-fm.height()>=0 ? int(boxes[i].top() - FONT_HEIGHT_MARGIN) : int(boxes[i].bottom() + height - FONT_HEIGHT_MARGIN); 278 | 279 | // Draw text background 280 | bPen.setColor(pen.color()); 281 | bBrush.setColor(pen.color()); 282 | p.setPen(bPen); 283 | p.setBrush(bBrush); 284 | p.drawRect(left,top,width,height); 285 | 286 | // Draw tex 287 | p.setPen(fPen); 288 | p.drawText(tLeft,tTop,text); 289 | } 290 | } 291 | } 292 | 293 | return image; 294 | } 295 | 296 | QString AuxUtils::getDefaultModelFilename() 297 | { 298 | return assetsPath + QDir::separator() + modelName; 299 | } 300 | 301 | QString AuxUtils::getDefaultLabelsFilename() 302 | { 303 | return assetsPath + QDir::separator() + labelsName; 304 | } 305 | 306 | QRectF AuxUtils::frameMatchImg(QImage img, QSize rectSize) 307 | { 308 | QSize isize = img.size(); 309 | rectSize.scale(isize, Qt::KeepAspectRatio); 310 | QPoint center = img.rect().center(); 311 | 312 | return QRectF(center.x()-rectSize.width()*0.5,center.y()-rectSize.height()*0.5,rectSize.width(),rectSize.height()); 313 | } 314 | 315 | bool AuxUtils::readLabels(QString filename) 316 | { 317 | if (!filename.trimmed().isEmpty()) 318 | { 319 | QFile textFile(filename); 320 | 321 | if (textFile.exists()) 322 | { 323 | QByteArray line; 324 | 325 | textFile.open(QIODevice::ReadOnly); 326 | 327 | line = textFile.readLine().trimmed(); 328 | while(!line.isEmpty()) // !textFile.atEnd() && 329 | { 330 | labels.append(line); 331 | line = textFile.readLine().trimmed(); 332 | } 333 | 334 | textFile.close(); 335 | if (labels.count()>0) labels.removeFirst(); 336 | return true; 337 | } 338 | } 339 | return false; 340 | } 341 | 342 | QStringList AuxUtils::getLabels() 343 | { 344 | if (labels.isEmpty()) readLabels(AuxUtils::getDefaultLabelsFilename()); 345 | 346 | return labels; 347 | } 348 | 349 | bool AuxUtils::isBGRvideoFrame(QVideoFrame f) 350 | { 351 | return f.pixelFormat() == QVideoFrame::Format_BGRA32 || 352 | f.pixelFormat() == QVideoFrame::Format_BGRA32_Premultiplied || 353 | f.pixelFormat() == QVideoFrame::Format_BGR32 || 354 | f.pixelFormat() == QVideoFrame::Format_BGR24 || 355 | f.pixelFormat() == QVideoFrame::Format_BGR565 || 356 | f.pixelFormat() == QVideoFrame::Format_BGR555 || 357 | f.pixelFormat() == QVideoFrame::Format_BGRA5658_Premultiplied; 358 | } 359 | 360 | bool AuxUtils::isBGRimage(QImage i) 361 | { 362 | return i.format() == QImage::Format_BGR30 || 363 | i.format() == QImage::Format_A2BGR30_Premultiplied; 364 | } 365 | 366 | QVariantList AuxUtils::networkInterfaces() 367 | { 368 | QVariantList list; 369 | 370 | foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces()) 371 | { 372 | if (!(interface.flags() & QNetworkInterface::IsLoopBack)) 373 | { 374 | QString info; 375 | 376 | info = interface.humanReadableName() + " (" + interface.name() + ") - " + interface.hardwareAddress() + " - " + 377 | (interface.addressEntries().count()>0 ? interface.addressEntries().first().ip().toString() : "None"); 378 | 379 | list << info; 380 | } 381 | } 382 | 383 | return list; 384 | } 385 | 386 | void AuxUtils::setAngleHor(double angle) { AuxUtils::angleHor = angle;} 387 | void AuxUtils::setAngleVer(double angle) { AuxUtils::angleVer = angle;} 388 | 389 | bool AuxUtils::setResolution(QString res) 390 | { 391 | QStringList sRes = res.split(RES_CHAR); 392 | 393 | if (sRes.count()>1) 394 | { 395 | width = sRes[0].toInt(); 396 | height = sRes[1].toInt(); 397 | } 398 | return false; 399 | } 400 | -------------------------------------------------------------------------------- /Configuration.qml: -------------------------------------------------------------------------------- 1 | import QtQuick 2.9 2 | import QtQuick.Controls 2.2 3 | 4 | Page { 5 | id: root 6 | title: qsTr("Settings") 7 | 8 | property double minConfidence 9 | property int nThreads 10 | property bool showInfTime 11 | property var tfObjects: [] 12 | property string resolution 13 | property var resolutions: [] 14 | property bool loadingRes 15 | 16 | readonly property int leftMargin: 100 17 | readonly property int rightMargin: 100 18 | 19 | signal objectChanged(string label, bool checked) 20 | signal resolutionUpdated() 21 | 22 | onResolutionsChanged: { 23 | console.log("Camera resolutions: " + resolutions) 24 | loadingRes = true 25 | sbResolution.to = resolutions.length - 1 26 | sbResolution.items = resolutions 27 | sbResolution.value = -1 28 | loadingRes = false 29 | sbResolution.value = sbResolution.valueFromText(resolution) 30 | } 31 | 32 | // TabBar 33 | footer: TabBar { 34 | id: tabBar 35 | currentIndex: swipeView.currentIndex 36 | 37 | TabButton { 38 | text: qsTr("Neural Network && Camera") 39 | } 40 | 41 | TabButton { 42 | text: qsTr("Screen info") 43 | } 44 | 45 | TabButton { 46 | text: qsTr("Hardware info && Close app") 47 | } 48 | } 49 | 50 | 51 | 52 | // tab contents 53 | SwipeView { 54 | id: swipeView 55 | anchors.fill: parent 56 | clip: true 57 | currentIndex: tabBar.currentIndex 58 | 59 | Flickable { 60 | contentHeight: column.height 61 | contentWidth: column.width 62 | 63 | flickableDirection: Flickable.VerticalFlick 64 | 65 | Column{ 66 | id: column 67 | width: root.width 68 | 69 | Item{ 70 | height: 20 71 | width: 1 72 | } 73 | 74 | Text{ 75 | anchors.leftMargin: leftMargin 76 | anchors.rightMargin: rightMargin 77 | anchors.horizontalCenter: parent.horizontalCenter 78 | horizontalAlignment: Text.AlignHCenter 79 | width: parent.width 80 | wrapMode: Text.WordWrap 81 | elide: Text.ElideRight 82 | text: qsTr("Minimum confidence") 83 | } 84 | 85 | Item{ 86 | width: 1 87 | height: 10 88 | } 89 | 90 | Slider{ 91 | id: slider 92 | anchors.horizontalCenter: parent.horizontalCenter 93 | width: parent.width - (leftMargin+rightMargin) 94 | from: 0 95 | to: 1 96 | value: minConfidence 97 | live: true 98 | 99 | onValueChanged: minConfidence = value 100 | } 101 | 102 | Text { 103 | anchors.leftMargin: leftMargin 104 | anchors.rightMargin: rightMargin 105 | anchors.horizontalCenter: parent.horizontalCenter 106 | horizontalAlignment: Text.AlignHCenter 107 | width: parent.width 108 | wrapMode: Text.WordWrap 109 | elide: Text.ElideRight 110 | text: Math.round(slider.position * 100) + " %" 111 | } 112 | 113 | Item{ 114 | width: 1 115 | height: 10 116 | } 117 | 118 | Row { 119 | width: parent.width 120 | spacing: 2 121 | 122 | Item{ 123 | height: 1 124 | width: (parent.width - parent.spacing - tThread.width)*0.5 125 | } 126 | 127 | Text{ 128 | id: tThread 129 | anchors.leftMargin: 30 130 | anchors.verticalCenter: parent.verticalCenter 131 | verticalAlignment: Text.AlignVCenter 132 | wrapMode: Text.WordWrap 133 | elide: Text.ElideRight 134 | text: qsTr("Number of threads") 135 | } 136 | } 137 | 138 | Slider{ 139 | id: sThreads 140 | anchors.horizontalCenter: parent.horizontalCenter 141 | width: parent.width - (leftMargin+rightMargin) 142 | from: 1 143 | to: auxUtils.numberThreads() 144 | enabled: to>1 145 | live: true 146 | snapMode: Slider.SnapAlways 147 | stepSize: 1 148 | value: nThreads 149 | 150 | onValueChanged: nThreads = value 151 | } 152 | 153 | Text { 154 | anchors.leftMargin: leftMargin 155 | anchors.rightMargin: rightMargin 156 | anchors.horizontalCenter: parent.horizontalCenter 157 | horizontalAlignment: Text.AlignHCenter 158 | width: parent.width 159 | wrapMode: Text.WordWrap 160 | elide: Text.ElideRight 161 | text: sThreads.value + " " + (sThreads.value>1 ? qsTr("threads") : qsTr("thread")) 162 | } 163 | 164 | Item{ 165 | width: 1 166 | height: 20 167 | } 168 | 169 | Text{ 170 | anchors.leftMargin: leftMargin 171 | anchors.rightMargin: rightMargin 172 | anchors.horizontalCenter: parent.horizontalCenter 173 | horizontalAlignment: Text.AlignHCenter 174 | width: parent.width 175 | wrapMode: Text.WordWrap 176 | elide: Text.ElideRight 177 | text: qsTr("Camera resolution") 178 | } 179 | 180 | Item{ 181 | width: 1 182 | height: 10 183 | } 184 | 185 | SpinBox { 186 | id: sbResolution 187 | anchors.horizontalCenter: parent.horizontalCenter 188 | from: 0 189 | editable: false 190 | property var items 191 | 192 | textFromValue: function(value) { 193 | return items[value]; 194 | } 195 | 196 | valueFromText: function(text) { 197 | for (var i = 0; i < items.length; i++) 198 | { 199 | if (items[i].toLowerCase() === text.toLowerCase()) 200 | return i 201 | } 202 | return value 203 | } 204 | 205 | onValueChanged: 206 | if (value>=0 && !loadingRes) 207 | { 208 | resolution = textFromValue(value) 209 | console.log("Resolution to save: " + resolution) 210 | resolutionUpdated() 211 | } 212 | } 213 | 214 | Item{ 215 | height: 30 216 | width: 1 217 | } 218 | } 219 | } 220 | 221 | Flickable { 222 | id: flickInfo 223 | contentHeight: column3.height 224 | contentWidth: column3.width 225 | 226 | flickableDirection: Flickable.VerticalFlick 227 | 228 | Column{ 229 | id: column3 230 | width: root.width 231 | 232 | Item{ 233 | height: 20 234 | width: 1 235 | } 236 | 237 | Text{ 238 | anchors.leftMargin: leftMargin 239 | anchors.rightMargin: rightMargin 240 | anchors.horizontalCenter: parent.horizontalCenter 241 | horizontalAlignment: Text.AlignHCenter 242 | width: parent.width 243 | wrapMode: Text.WordWrap 244 | elide: Text.ElideRight 245 | text: qsTr("General information") 246 | } 247 | 248 | Item{ 249 | width: 1 250 | height: 10 251 | } 252 | 253 | Row{ 254 | width: parent.width - (leftMargin+rightMargin) 255 | anchors.horizontalCenter: parent.horizontalCenter 256 | spacing: width - tShowInfTime.width - sShowInfTime.width 257 | 258 | Text { 259 | id: tShowInfTime 260 | text: qsTr("Show inference time") 261 | anchors.verticalCenter: parent.verticalCenter 262 | verticalAlignment: Text.AlignVCenter 263 | } 264 | 265 | Switch{ 266 | anchors.verticalCenter: parent.verticalCenter 267 | id: sShowInfTime 268 | checked: showInfTime 269 | 270 | onToggled: showInfTime = checked 271 | } 272 | } 273 | 274 | Item{ 275 | height: 20 276 | width: 1 277 | } 278 | 279 | Text{ 280 | anchors.leftMargin: leftMargin 281 | anchors.rightMargin: rightMargin 282 | anchors.horizontalCenter: parent.horizontalCenter 283 | horizontalAlignment: Text.AlignHCenter 284 | width: parent.width 285 | wrapMode: Text.WordWrap 286 | elide: Text.ElideRight 287 | text: qsTr("Detected objects") 288 | } 289 | 290 | Item{ 291 | width: 1 292 | height: 10 293 | } 294 | 295 | Repeater{ 296 | model: auxUtils.getLabels() 297 | 298 | Column{ 299 | width: root.width 300 | 301 | Row{ 302 | width: parent.width - (leftMargin+rightMargin) 303 | anchors.horizontalCenter: parent.horizontalCenter 304 | spacing: width - rObject.width - sObject.width 305 | 306 | 307 | Row { 308 | id: rObject 309 | spacing: 2 310 | width: tObject.width + spacing 311 | 312 | Text { 313 | id: tObject 314 | text: modelData.replace(/\b\w/g, function(l){ return l.toUpperCase() }) 315 | anchors.verticalCenter: parent.verticalCenter 316 | verticalAlignment: Text.AlignVCenter 317 | wrapMode: Text.NoWrap 318 | elide: Text.ElideRight 319 | } 320 | } 321 | 322 | Switch{ 323 | anchors.verticalCenter: parent.verticalCenter 324 | id: sObject 325 | checked: tfObjects[modelData] 326 | onToggled: objectChanged(modelData,checked) 327 | } 328 | 329 | } 330 | 331 | Item{ 332 | width: 1 333 | height: 10 334 | } 335 | } 336 | 337 | } 338 | } 339 | } 340 | 341 | Flickable { 342 | contentHeight: column2.height 343 | contentWidth: column2.width 344 | 345 | flickableDirection: Flickable.VerticalFlick 346 | 347 | Column{ 348 | id: column2 349 | width: root.width 350 | 351 | Item{ 352 | height: 20 353 | width: 1 354 | } 355 | 356 | Text{ 357 | anchors.leftMargin: leftMargin 358 | anchors.rightMargin: rightMargin 359 | anchors.horizontalCenter: parent.horizontalCenter 360 | horizontalAlignment: Text.AlignHCenter 361 | width: parent.width 362 | wrapMode: Text.WordWrap 363 | elide: Text.ElideRight 364 | height: 30 365 | text: qsTr("Hardware info") 366 | } 367 | 368 | Item{ 369 | width: 1 370 | height: 10 371 | } 372 | 373 | Column{ 374 | width: root.width 375 | 376 | Repeater{ 377 | model: auxUtils.networkInterfaces() 378 | 379 | Text{ 380 | anchors.leftMargin: leftMargin 381 | anchors.rightMargin: rightMargin 382 | horizontalAlignment: Text.AlignHCenter 383 | width: parent.width 384 | height: 30 385 | wrapMode: Text.WordWrap 386 | elide: Text.ElideRight 387 | text: modelData 388 | } 389 | } 390 | } 391 | 392 | Item{ 393 | width: 1 394 | height: 30 395 | } 396 | 397 | Button{ 398 | id: bClose 399 | anchors.horizontalCenter: parent.horizontalCenter 400 | text: qsTr("Close app") 401 | onClicked: dialog.open() 402 | 403 | contentItem: Text { 404 | text: bClose.text 405 | font: bClose.font 406 | opacity: enabled ? 1.0 : 0.3 407 | color: "white" 408 | horizontalAlignment: Text.AlignHCenter 409 | verticalAlignment: Text.AlignVCenter 410 | elide: Text.ElideRight 411 | } 412 | 413 | background: Rectangle { 414 | implicitWidth: 100 415 | implicitHeight: 40 416 | color: bClose.down ? "#ff0000" : "#aa0000" 417 | border.color: "#7e181a" 418 | border.width: 1 419 | radius: 0 420 | } 421 | } 422 | } 423 | } 424 | 425 | } 426 | 427 | Rectangle{ 428 | id: backPageIndicator 429 | anchors.bottom: parent.bottom 430 | height: 20 431 | width: parent.width 432 | } 433 | 434 | PageIndicator { 435 | id: pageIndicator 436 | count: swipeView.count 437 | currentIndex: swipeView.currentIndex 438 | anchors.centerIn: backPageIndicator 439 | 440 | delegate: Rectangle{ 441 | implicitWidth: 10 442 | implicitHeight: 10 443 | radius: width 444 | } 445 | } 446 | 447 | Dialog { 448 | id: dialog 449 | x: 0.5*(parent.width - width) 450 | y: 0.5*(parent.height - height) 451 | title: "Close app" 452 | standardButtons: Dialog.Ok | Dialog.Cancel 453 | modal: true 454 | 455 | Label{ 456 | text: qsTr("Do you really want to close this app?") 457 | } 458 | 459 | onAccepted: Qt.callLater(Qt.quit) 460 | onRejected: dialog.close() 461 | } 462 | } 463 | -------------------------------------------------------------------------------- /cpp/tensorflow.cpp: -------------------------------------------------------------------------------- 1 | #include "tensorflow.h" 2 | 3 | #include "tensorflow/lite/kernels/internal/tensor.h" 4 | #include "tensorflow/lite/kernels/internal/tensor_utils.h" 5 | 6 | #include "get_top_n.h" 7 | #include "colormanager.h" 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | TensorFlow::TensorFlow(QObject *parent) : QObject(parent) 18 | { 19 | initialized = false; 20 | accelaration = false; 21 | verbose = false; 22 | numThreads = 1; 23 | threshold = 0.1; 24 | has_detection_masks = false; 25 | } 26 | TensorFlow::~TensorFlow() 27 | {} 28 | 29 | template 30 | bool formatImageQt(T* out, QImage image, int image_channels, int wanted_height, int wanted_width, int wanted_channels, bool input_floating, bool scale = false) 31 | { 32 | const float input_mean = 127.5f; 33 | const float input_std = 127.5f; 34 | 35 | // Check same number of channels 36 | if (image_channels != wanted_channels) 37 | { 38 | qDebug() << "ERROR: the image has" << image_channels << " channels. Wanted channels:" << wanted_channels; 39 | return false; 40 | } 41 | 42 | // Scale image if needed 43 | if (scale && (image.width() != wanted_width || image.height() != wanted_height)) 44 | image = image.scaled(wanted_height,wanted_width,Qt::IgnoreAspectRatio,Qt::FastTransformation); 45 | 46 | // Number of pixels 47 | const int numberPixels = image.height()*image.width()*wanted_channels; 48 | 49 | // Pointer to image data 50 | const uint8_t *output = image.bits(); 51 | 52 | // Boolean to [0,1] 53 | const int inputFloat = input_floating ? 1 : 0; 54 | const int inputInt = input_floating ? 0 : 1; 55 | 56 | // Transform to [0,128] ¿? 57 | for (int i = 0; i < numberPixels; i++) 58 | { 59 | out[i] = inputFloat*((output[i] - input_mean) / input_std) + // inputFloat*(output[i]/ 128.f - 1.f) + 60 | inputInt*(uint8_t)output[i]; 61 | //qDebug() << out[i]; 62 | } 63 | 64 | return true; 65 | } 66 | 67 | // ----------------------------------------------------------------------------------------------------------------------- 68 | // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lite/examples/label_image/bitmap_helpers_impl.h 69 | // ----------------------------------------------------------------------------------------------------------------------- 70 | template 71 | void formatImageTFLite(T* out, const uint8_t* in, int image_height, int image_width, int image_channels, int wanted_height, int wanted_width, int wanted_channels, bool input_floating) 72 | { 73 | const float input_mean = 127.5f; 74 | const float input_std = 127.5f; 75 | 76 | int number_of_pixels = image_height * image_width * image_channels; 77 | std::unique_ptr interpreter(new Interpreter); 78 | 79 | int base_index = 0; 80 | 81 | // two inputs: input and new_sizes 82 | interpreter->AddTensors(2, &base_index); 83 | 84 | // one output 85 | interpreter->AddTensors(1, &base_index); 86 | 87 | // set input and output tensors 88 | interpreter->SetInputs({0, 1}); 89 | interpreter->SetOutputs({2}); 90 | 91 | // set parameters of tensors 92 | TfLiteQuantizationParams quant; 93 | interpreter->SetTensorParametersReadWrite(0, kTfLiteFloat32, "input", {1, image_height, image_width, image_channels}, quant); 94 | interpreter->SetTensorParametersReadWrite(1, kTfLiteInt32, "new_size", {2},quant); 95 | interpreter->SetTensorParametersReadWrite(2, kTfLiteFloat32, "output", {1, wanted_height, wanted_width, wanted_channels}, quant); 96 | 97 | ops::builtin::BuiltinOpResolver resolver; 98 | const TfLiteRegistration *resize_op = resolver.FindOp(BuiltinOperator_RESIZE_BILINEAR,1); 99 | auto* params = reinterpret_cast(malloc(sizeof(TfLiteResizeBilinearParams))); 100 | params->align_corners = false; 101 | interpreter->AddNodeWithParameters({0, 1}, {2}, nullptr, 0, params, resize_op, nullptr); 102 | interpreter->AllocateTensors(); 103 | 104 | 105 | // fill input image 106 | // in[] are integers, cannot do memcpy() directly 107 | auto input = interpreter->typed_tensor(0); 108 | for (int i = 0; i < number_of_pixels; i++) 109 | input[i] = in[i]; 110 | 111 | // fill new_sizes 112 | interpreter->typed_tensor(1)[0] = wanted_height; 113 | interpreter->typed_tensor(1)[1] = wanted_width; 114 | 115 | interpreter->Invoke(); 116 | 117 | auto output = interpreter->typed_tensor(2); 118 | auto output_number_of_pixels = wanted_height * wanted_height * wanted_channels; 119 | 120 | for (int i = 0; i < output_number_of_pixels; i++) 121 | { 122 | if (input_floating) 123 | out[i] = (output[i] - input_mean) / input_std; 124 | else 125 | out[i] = (uint8_t)output[i]; 126 | } 127 | } 128 | bool TensorFlow::init(int imgHeight, int imgWidth) 129 | { 130 | if (!initialized) 131 | initialized = initTFLite(imgHeight,imgWidth); 132 | 133 | return initialized; 134 | } 135 | 136 | void TensorFlow::initInput(int imgHeight, int imgWidth) 137 | { 138 | Q_UNUSED(imgHeight); 139 | Q_UNUSED(imgWidth); 140 | } 141 | 142 | // ------------------------------------------------------------------------------------------------------------------------------ 143 | // Adapted from: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/lite/examples/label_image/label_image.cc 144 | // ------------------------------------------------------------------------------------------------------------------------------ 145 | bool TensorFlow::initTFLite(int imgHeight, int imgWidth) 146 | { 147 | Q_UNUSED(imgHeight); 148 | Q_UNUSED(imgWidth); 149 | 150 | try{ 151 | // Open model & assign error reporter 152 | model = AuxUtils::getDefaultModelFilename().trimmed().isEmpty() && AuxUtils::getDefaultLabelsFilename().trimmed().isEmpty() ? nullptr : 153 | FlatBufferModel::BuildFromFile(filename.toStdString().c_str(),&error_reporter); 154 | 155 | if(model == nullptr) 156 | { 157 | qDebug() << "TensorFlow model loading: ERROR"; 158 | return false; 159 | } 160 | 161 | // Link model & resolver 162 | InterpreterBuilder builder(*model.get(), resolver); 163 | 164 | // Check interpreter 165 | if(builder(&interpreter) != kTfLiteOk) 166 | { 167 | qDebug() << "Interpreter: ERROR"; 168 | return false; 169 | } 170 | 171 | // Apply accelaration (Neural Network Android) 172 | interpreter->UseNNAPI(accelaration); 173 | 174 | if(interpreter->AllocateTensors() != kTfLiteOk) 175 | { 176 | qDebug() << "Allocate tensors: ERROR"; 177 | return false; 178 | } 179 | 180 | // Set kind of network 181 | kind_network = interpreter->outputs().size()>1 ? knOBJECT_DETECTION : knIMAGE_CLASSIFIER; 182 | 183 | if (verbose) 184 | { 185 | int i_size = interpreter->inputs().size(); 186 | int o_size = interpreter->outputs().size(); 187 | int t_size = interpreter->tensors_size(); 188 | 189 | qDebug() << "tensors size: " << t_size; 190 | qDebug() << "nodes size: " << interpreter->nodes_size(); 191 | qDebug() << "inputs: " << i_size; 192 | qDebug() << "outputs: " << o_size; 193 | 194 | for (int i = 0; i < i_size; i++) 195 | qDebug() << "input" << i << "name:" << interpreter->GetInputName(i) << ", type:" << interpreter->tensor(interpreter->inputs()[i])->type; 196 | 197 | for (int i = 0; i < o_size; i++) 198 | qDebug() << "output" << i << "name:" << interpreter->GetOutputName(i) << ", type:" << interpreter->tensor(interpreter->outputs()[i])->type; 199 | 200 | for (int i = 0; i < t_size; i++) 201 | { 202 | if (interpreter->tensor(i)->name) 203 | qDebug() << i << ":" << interpreter->tensor(i)->name << "," 204 | << interpreter->tensor(i)->bytes << "," 205 | << interpreter->tensor(i)->type << "," 206 | << interpreter->tensor(i)->params.scale << "," 207 | << interpreter->tensor(i)->params.zero_point; 208 | } 209 | } 210 | 211 | // Get input dimension from the input tensor metadata 212 | // Assuming one input only 213 | int input = interpreter->inputs()[0]; 214 | TfLiteIntArray* dims = interpreter->tensor(input)->dims; 215 | 216 | // Save outputs 217 | outputs.clear(); 218 | for(unsigned int i=0;ioutputs().size();i++) 219 | outputs.push_back(interpreter->tensor(interpreter->outputs()[i])); 220 | 221 | wanted_height = dims->data[1]; 222 | wanted_width = dims->data[2]; 223 | wanted_channels = dims->data[3]; 224 | 225 | if (verbose) 226 | { 227 | qDebug() << "Wanted height:" << wanted_height; 228 | qDebug() << "Wanted width:" << wanted_width; 229 | qDebug() << "Wanted channels:" << wanted_channels; 230 | } 231 | 232 | if (numThreads > 1) 233 | interpreter->SetNumThreads(numThreads); 234 | 235 | // Read labels 236 | if (readLabels()) qDebug() << "There are" << labels.count() << "labels."; 237 | else qDebug() << "There are NO labels"; 238 | 239 | qDebug() << "Tensorflow initialization: OK"; 240 | return true; 241 | 242 | }catch(...) 243 | { 244 | qDebug() << "Exception loading model"; 245 | return false; 246 | } 247 | } 248 | 249 | // -------------------------------------------------------------------------------------- 250 | // Code from: https://github.com/YijinLiu/tf-cpu/blob/master/benchmark/obj_detect_lite.cc 251 | // -------------------------------------------------------------------------------------- 252 | template 253 | T* TensorData(TfLiteTensor* tensor, int batch_index); 254 | 255 | template<> 256 | float* TensorData(TfLiteTensor* tensor, int batch_index) { 257 | int nelems = 1; 258 | for (int i = 1; i < tensor->dims->size; i++) nelems *= tensor->dims->data[i]; 259 | switch (tensor->type) { 260 | case kTfLiteFloat32: 261 | return tensor->data.f + nelems * batch_index; 262 | default: 263 | qDebug() << "Should not reach here!"; 264 | } 265 | return nullptr; 266 | } 267 | 268 | template<> 269 | uint8_t* TensorData(TfLiteTensor* tensor, int batch_index) { 270 | int nelems = 1; 271 | for (int i = 1; i < tensor->dims->size; i++) nelems *= tensor->dims->data[i]; 272 | switch (tensor->type) { 273 | case kTfLiteUInt8: 274 | return tensor->data.uint8 + nelems * batch_index; 275 | default: 276 | qDebug() << "Should not reach here!"; 277 | } 278 | return nullptr; 279 | } 280 | 281 | int TensorFlow::getKindNetwork() 282 | { 283 | return kind_network; 284 | } 285 | 286 | double TensorFlow::getThreshold() const 287 | { 288 | return threshold; 289 | } 290 | 291 | void TensorFlow::setThreshold(double value) 292 | { 293 | threshold = value; 294 | } 295 | 296 | bool TensorFlow::setInputs(QImage image) 297 | { 298 | return setInputsTFLite(image); 299 | } 300 | 301 | bool TensorFlow::setInputsTFLite(QImage image) 302 | { 303 | // Get inputs 304 | std::vector inputs = interpreter->inputs(); 305 | 306 | // Set inputs 307 | for(unsigned int i=0;iinputs().size();i++) 308 | { 309 | int input = inputs[i]; 310 | 311 | // Convert input 312 | switch (interpreter->tensor(input)->type) 313 | { 314 | case kTfLiteFloat32: 315 | { 316 | formatImageTFLite(interpreter->typed_tensor(input),image.bits(), image.height(), 317 | image.width(), img_channels, wanted_height, wanted_width,wanted_channels, true); 318 | //formatImageQt(interpreter->typed_tensor(input),image,img_channels, 319 | // wanted_height,wanted_width,wanted_channels,true,true); 320 | break; 321 | } 322 | case kTfLiteUInt8: 323 | { 324 | formatImageTFLite(interpreter->typed_tensor(input),image.bits(), 325 | img_height, img_width, img_channels, wanted_height, 326 | wanted_width, wanted_channels, false); 327 | 328 | //formatImageQt(interpreter->typed_tensor(input),image,img_channels, 329 | // wanted_height,wanted_width,wanted_channels,false); 330 | break; 331 | } 332 | default: 333 | { 334 | qDebug() << "Cannot handle input type" << interpreter->tensor(input)->type << "yet"; 335 | return false; 336 | } 337 | } 338 | } 339 | 340 | return true; 341 | } 342 | 343 | bool TensorFlow::inference() 344 | { 345 | return inferenceTFLite(); 346 | } 347 | 348 | bool TensorFlow::inferenceTFLite() 349 | { 350 | // Invoke interpreter 351 | if (interpreter->Invoke() != kTfLiteOk) 352 | { 353 | qDebug() << "Failed to invoke interpreter"; 354 | return false; 355 | } 356 | return true; 357 | } 358 | bool TensorFlow::getClassfierOutputs(std::vector> *top_results) 359 | { 360 | return getClassfierOutputsTFLite(top_results); 361 | } 362 | 363 | bool TensorFlow::getClassfierOutputsTFLite(std::vector> *top_results) 364 | { 365 | const int output_size = 1000; 366 | const size_t num_results = 5; 367 | 368 | // Assume one output 369 | if (interpreter->outputs().size()>0) 370 | { 371 | int output = interpreter->outputs()[0]; 372 | 373 | switch (interpreter->tensor(output)->type) 374 | { 375 | case kTfLiteFloat32: 376 | { 377 | tflite::label_image::get_top_n(interpreter->typed_output_tensor(0), output_size, 378 | num_results, threshold, top_results, true); 379 | break; 380 | } 381 | case kTfLiteUInt8: 382 | { 383 | tflite::label_image::get_top_n(interpreter->typed_output_tensor(0), 384 | output_size, num_results, threshold, top_results,false); 385 | break; 386 | } 387 | default: 388 | { 389 | qDebug() << "Cannot handle output type" << interpreter->tensor(output)->type << "yet"; 390 | return false; 391 | } 392 | } 393 | return true; 394 | } 395 | return false; 396 | } 397 | 398 | 399 | bool TensorFlow::getObjectOutputs(QStringList &captions, QList &confidences, QList &locations, QList &images) 400 | { 401 | return getObjectOutputsTFLite(captions,confidences,locations,images); 402 | } 403 | 404 | bool TensorFlow::getObjectOutputsTFLite(QStringList &captions, QList &confidences, QList &locations, QList &masks) 405 | { 406 | if (outputs.size() >= 4) 407 | { 408 | const int num_detections = *TensorData(outputs[3], 0); 409 | const float* detection_classes = TensorData(outputs[1], 0); 410 | const float* detection_scores = TensorData(outputs[2], 0); 411 | const float* detection_boxes = TensorData(outputs[0], 0); 412 | const float* detection_masks = !has_detection_masks || outputs.size()<5 ? nullptr : TensorData(outputs[4], 0); 413 | ColorManager cm; 414 | 415 | for (int i=0; idims->data[2]; 447 | const int dim2 = outputs[4]->dims->data[3]; 448 | QImage mask(dim1,dim2,QImage::Format_ARGB32_Premultiplied); 449 | 450 | // Set binary mask [dim1,dim2] 451 | for(int j=0;j= MASK_THRESHOLD ? 454 | cm.getColor(label).rgba() : QColor(Qt::transparent).rgba()); 455 | 456 | // Billinear interpolation 457 | // https://chu24688.tian.yam.com/posts/44797337 458 | //QImage maskScaled = ColorManager::billinearInterpolation(mask,box.height(),box.width()); 459 | 460 | // Scale mask to box size 461 | QImage maskScaled = mask.scaled(box.width(),box.height(),Qt::IgnoreAspectRatio,Qt::FastTransformation); 462 | 463 | // Border detection 464 | //QTransform trans(-1,0,1,-2,0,2,-1,0,1); 465 | //maskScaled = ColorManager::applyTransformation(maskScaled,trans); 466 | 467 | // Append to masks 468 | masks.append(maskScaled); 469 | } 470 | 471 | // Save remaining data 472 | captions.append(label); 473 | confidences.append(score); 474 | locations.append(box); 475 | } 476 | 477 | return true; 478 | } 479 | return false; 480 | } 481 | 482 | // --------------------------------------------------------------------------------------------------------------- 483 | // Adapted from: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/lite/examples/label_image 484 | // --------------------------------------------------------------------------------------------------------------- 485 | bool TensorFlow::run(QImage img) 486 | { 487 | QElapsedTimer timer; 488 | 489 | if (initialized) 490 | { 491 | // Start timer 492 | //timer.start(); 493 | 494 | // Transform image format & copy data 495 | QImage image = img.format() == format ? img : img.convertToFormat(format); 496 | 497 | // Store original image properties 498 | img_width = image.width(); 499 | img_height = image.height(); 500 | img_channels = numChannels; 501 | 502 | // Set inputs 503 | if (!setInputs(image)) return false; 504 | 505 | // Perform inference 506 | timer.start(); 507 | if (!inference()) return false; 508 | inferenceTime = timer.elapsed(); 509 | 510 | // ------------------------------------- 511 | // Outputs depend on the kind of network 512 | // ------------------------------------- 513 | rCaption.clear(); 514 | rConfidence.clear(); 515 | rBox.clear(); 516 | rMasks.clear(); 517 | //inferenceTime = 0; 518 | 519 | // Image classifier 520 | if (kind_network == knIMAGE_CLASSIFIER) 521 | { 522 | std::vector> top_results; 523 | 524 | if (!getClassfierOutputs(&top_results)) return false; 525 | 526 | for (const auto& result : top_results) 527 | { 528 | rConfidence.append(result.first); 529 | rCaption.append(getLabel(result.second)); 530 | if (verbose) qDebug() << rConfidence.last() << ":" << rCaption.last(); 531 | } 532 | } 533 | // Object detection 534 | else if (kind_network == knOBJECT_DETECTION) 535 | { 536 | if (!getObjectOutputs(rCaption,rConfidence,rBox,rMasks)) return false; 537 | } 538 | 539 | //inferenceTime = timer.elapsed(); 540 | if (verbose) qDebug() << "Elapsed time: " << inferenceTime << "milliseconds"; 541 | 542 | return true; 543 | } 544 | 545 | return false; 546 | } 547 | 548 | // WARNING: function repeated in AuxUtils 549 | bool TensorFlow::readLabels() 550 | { 551 | if (!labelsFilename.trimmed().isEmpty()) 552 | { 553 | QFile textFile(labelsFilename); 554 | 555 | if (textFile.exists()) 556 | { 557 | QByteArray line; 558 | 559 | labels.clear(); 560 | textFile.open(QIODevice::ReadOnly); 561 | 562 | line = textFile.readLine().trimmed(); 563 | while(!line.isEmpty()) // !textFile.atEnd() && 564 | { 565 | labels.append(line); 566 | line = textFile.readLine().trimmed(); 567 | } 568 | 569 | textFile.close(); 570 | } 571 | return true; 572 | } 573 | return false; 574 | } 575 | 576 | QString TensorFlow::getLabel(int index) 577 | { 578 | if(index>=0 && index=0 && index TensorFlow::getConfidence() 596 | { 597 | return rConfidence; 598 | } 599 | 600 | QList TensorFlow::getBoxes() 601 | { 602 | return rBox; 603 | } 604 | 605 | QList TensorFlow::getMasks() 606 | { 607 | return rMasks; 608 | } 609 | 610 | int TensorFlow::getInferenceTime() 611 | { 612 | return inferenceTime; 613 | } 614 | 615 | double TensorFlow::getResultConfidence(int index) 616 | { 617 | if (index>=0 && index 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------