1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/* ============================================================
 *
 * This file is a part of digiKam
 *
 * Date        : 2019-08-08
 * Description : Derived class to perform YuNet neural network inference
 *               for face detection. Credit: Ayoosh Kathuria (for YuNet blog post),
 *               sthanhng (for example of face detection with YuNet).
 *               More information with YuNetv3:
 *               https://github.com/opencv/opencv_zoo/tree/main/models/face_detection_yunet
 *
 * SPDX-FileCopyrightText: 2019      by Thanh Trung Dinh <dinhthanhtrung1996 at gmail dot com>
 * SPDX-FileCopyrightText: 2020-2024 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * SPDX-FileCopyrightText: 2024      by Michael Miller <michael underscore miller at msn dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "dnnfacedetectoryunet.h"

// Qt includes

#include <QList>
#include <QRect>
#include <QString>
#include <QFileInfo>
#include <QMutexLocker>
#include <QElapsedTimer>
#include <QStandardPaths>

// Local includes

#include "digikam_debug.h"
#include "digikam_config.h"
#include "dnnmodelyunet.h"

namespace Digikam
{

const std::map<FaceScanSettings::FaceDetectionSize, int> faceenum2size
{
    { FaceScanSettings::FaceDetectionSize::ExtraLarge, 420   },
    { FaceScanSettings::FaceDetectionSize::Large,      620   },
    { FaceScanSettings::FaceDetectionSize::Medium,     800   },
    { FaceScanSettings::FaceDetectionSize::Small,      1200  },
    { FaceScanSettings::FaceDetectionSize::ExtraSmall, 2000  }
};

DNNFaceDetectorYuNet::DNNFaceDetectorYuNet()
    : DNNFaceDetectorBase(1.0F / 255.0F,
                          cv::Scalar(0.0, 0.0, 0.0),
                          cv::Size(800, 800))
{
    qCDebug(DIGIKAM_FACESENGINE_LOG) << "Creating new instance of DNNFaceDetectorYuNet";

    loadModels();
}

DNNFaceDetectorYuNet::~DNNFaceDetectorYuNet()
{
}

bool DNNFaceDetectorYuNet::loadModels()
{

   model = DNNModelManager::instance()->getModel(QLatin1String("YuNet"), DNNModelUsage::DNNUsageFaceDetection);

    if (!(model->modelLoaded))
    {
        try
        {

            cv::Ptr<cv::FaceDetectorYN> net = static_cast<DNNModelYuNet*>(model)->getNet();<--- Shadow variable
            qCDebug(DIGIKAM_FACESENGINE_LOG) << "YuNet model:" << model;

        }
        catch (cv::Exception& e)
        {
            qCWarning(DIGIKAM_FACESENGINE_LOG) << "cv::Exception:" << e.what();

            return false;
        }
        catch (...)
        {
           qCWarning(DIGIKAM_FACESENGINE_LOG) << "Default exception from OpenCV";

           return false;
        }
    }
    else
    {
        qCCritical(DIGIKAM_FACESENGINE_LOG) << "Cannot find faces engine DNN model" << model;
        qCCritical(DIGIKAM_FACESENGINE_LOG) << "Faces detection feature cannot be used!";

        return false;
    }

    return true;
}

cv::Mat DNNFaceDetectorYuNet::callModel(const cv::Mat& inputImage)
{
    QElapsedTimer timer;
    cv::Mat faces;

    qCDebug(DIGIKAM_FACESENGINE_LOG) << "starting YuNet face detection";

    // Lock the model for single threading

    QMutexLocker lock(&(model->mutex));

    try
    {
        if (model->modelLoaded)
        {
            // Start the timer so we know how long we're locking for

            timer.start();

            // Set up the detector with new params

            static_cast<DNNModelYuNet*>(model)->getNet()->setInputSize(inputImage.size());
            static_cast<DNNModelYuNet*>(model)->getNet()->setScoreThreshold(confidenceThreshold);
            static_cast<DNNModelYuNet*>(model)->getNet()->setNMSThreshold(nmsThreshold);

            // Detect faces

            static_cast<DNNModelYuNet*>(model)->getNet()->detect(inputImage, faces);

            qCDebug(DIGIKAM_FACESENGINE_LOG) << "YuNet detected" << faces.rows << "faces in" << timer.elapsed() << "ms";
        }
    }

    catch (const std::exception& ex)
    {
        // ...
    }
    catch (const std::string& ex)
    {
        // ...
    }
    catch (...)
    {
        qCCritical(DIGIKAM_FACESENGINE_LOG) << "Face detection encountered a critical error. Reloading model...";
        loadModels();
    }

    return faces;
}

void DNNFaceDetectorYuNet::detectFaces(const cv::Mat& inputImage,
                                       const cv::Size& paddedSize,
                                       std::vector<cv::Rect>& detectedBboxes)
{
    Q_UNUSED(paddedSize);

    std::vector<float> confidences;

    // Safety check

    if (inputImage.empty())
    {
        qCDebug(DIGIKAM_FACESENGINE_LOG) << "Invalid image given to YuNet, not detecting faces.";
        return;
    }

    // All calls to the model need to be in this method

    cv::Mat faces = callModel(inputImage);

    // Process faces found

    if ( faces.rows > 0)
    {
        // Loop through the faces found

        for (int i = 0 ; i < faces.rows ; ++i)
        {
            double confidence = faces.at<float>(i, 14);

            // Add the confidence to the result list

            confidences.push_back(confidence);

            // Create the rect of the face

            int X       = static_cast<int>(faces.at<float>(i, 0));
            int Y       = static_cast<int>(faces.at<float>(i, 1));
            int width   = static_cast<int>(faces.at<float>(i, 2));
            int height  = static_cast<int>(faces.at<float>(i, 3));

            // Add the rect to result list

            detectedBboxes.push_back(cv::Rect(X, Y, width, height));
        }
    }
}

void DNNFaceDetectorYuNet::setFaceDetectionSize(FaceScanSettings::FaceDetectionSize faceSize)
{
    try
    {
        inputImageSize = cv::Size(
                                  faceenum2size.at(faceSize),
                                  faceenum2size.at(faceSize)
                                 );
    }
    catch (const std::exception& e)
    {
        qCDebug(DIGIKAM_FACESENGINE_LOG) << "YuNet face size error:" << e.what() << '\n';
    }
}

} // namespace Digikam