test_common.impl.hpp 13.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

// Used in accuracy and perf tests as a content of .cpp file
// Note: don't use "precomp.hpp" here
#include "opencv2/ts.hpp"
#include "opencv2/ts/ts_perf.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/core/ocl.hpp"

#include "opencv2/dnn.hpp"
#include "test_common.hpp"

#include <opencv2/core/utils/configuration.private.hpp>
#include <opencv2/core/utils/logger.hpp>

namespace cv { namespace dnn {
CV__DNN_EXPERIMENTAL_NS_BEGIN

void PrintTo(const cv::dnn::Backend& v, std::ostream* os)
{
    switch (v) {
24 25 26 27 28 29 30
        case DNN_BACKEND_DEFAULT: *os << "DEFAULT"; return;
        case DNN_BACKEND_HALIDE: *os << "HALIDE"; return;
        case DNN_BACKEND_INFERENCE_ENGINE: *os << "DLIE*"; return;
        case DNN_BACKEND_OPENCV: *os << "OCV"; return;
        case DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019: *os << "DLIE"; return;
        case DNN_BACKEND_INFERENCE_ENGINE_NGRAPH: *os << "NGRAPH"; return;
        default: /* do nothing */;
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
    } // don't use "default:" to emit compiler warnings
    *os << "DNN_BACKEND_UNKNOWN(" << (int)v << ")";
}

void PrintTo(const cv::dnn::Target& v, std::ostream* os)
{
    switch (v) {
    case DNN_TARGET_CPU: *os << "CPU"; return;
    case DNN_TARGET_OPENCL: *os << "OCL"; return;
    case DNN_TARGET_OPENCL_FP16: *os << "OCL_FP16"; return;
    case DNN_TARGET_MYRIAD: *os << "MYRIAD"; return;
    case DNN_TARGET_FPGA: *os << "FPGA"; return;
    } // don't use "default:" to emit compiler warnings
    *os << "DNN_TARGET_UNKNOWN(" << (int)v << ")";
}

void PrintTo(const tuple<cv::dnn::Backend, cv::dnn::Target> v, std::ostream* os)
{
    PrintTo(get<0>(v), os);
    *os << "/";
    PrintTo(get<1>(v), os);
}

CV__DNN_EXPERIMENTAL_NS_END
}} // namespace



namespace opencv_test {

void normAssert(
        cv::InputArray ref, cv::InputArray test, const char *comment /*= ""*/,
        double l1 /*= 0.00001*/, double lInf /*= 0.0001*/)
{
    double normL1 = cvtest::norm(ref, test, cv::NORM_L1) / ref.getMat().total();
66
    EXPECT_LE(normL1, l1) << comment << "  |ref| = " << cvtest::norm(ref, cv::NORM_INF);
67 68

    double normInf = cvtest::norm(ref, test, cv::NORM_INF);
69
    EXPECT_LE(normInf, lInf) << comment << "  |ref| = " << cvtest::norm(ref, cv::NORM_INF);
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
}

std::vector<cv::Rect2d> matToBoxes(const cv::Mat& m)
{
    EXPECT_EQ(m.type(), CV_32FC1);
    EXPECT_EQ(m.dims, 2);
    EXPECT_EQ(m.cols, 4);

    std::vector<cv::Rect2d> boxes(m.rows);
    for (int i = 0; i < m.rows; ++i)
    {
        CV_Assert(m.row(i).isContinuous());
        const float* data = m.ptr<float>(i);
        double l = data[0], t = data[1], r = data[2], b = data[3];
        boxes[i] = cv::Rect2d(l, t, r - l, b - t);
    }
    return boxes;
}

void normAssertDetections(
        const std::vector<int>& refClassIds,
        const std::vector<float>& refScores,
        const std::vector<cv::Rect2d>& refBoxes,
        const std::vector<int>& testClassIds,
        const std::vector<float>& testScores,
        const std::vector<cv::Rect2d>& testBoxes,
        const char *comment /*= ""*/, double confThreshold /*= 0.0*/,
        double scores_diff /*= 1e-5*/, double boxes_iou_diff /*= 1e-4*/)
{
99
    ASSERT_FALSE(testClassIds.empty()) << "No detections";
100
    std::vector<bool> matchedRefBoxes(refBoxes.size(), false);
101
    std::vector<double> refBoxesIoUDiff(refBoxes.size(), 1.0);
102 103
    for (int i = 0; i < testBoxes.size(); ++i)
    {
104
        //cout << "Test[i=" << i << "]: score=" << testScores[i] << " id=" << testClassIds[i] << " box " << testBoxes[i] << endl;
105 106 107 108 109 110 111
        double testScore = testScores[i];
        if (testScore < confThreshold)
            continue;

        int testClassId = testClassIds[i];
        const cv::Rect2d& testBox = testBoxes[i];
        bool matched = false;
112
        double topIoU = 0;
113 114 115 116 117 118 119
        for (int j = 0; j < refBoxes.size() && !matched; ++j)
        {
            if (!matchedRefBoxes[j] && testClassId == refClassIds[j] &&
                std::abs(testScore - refScores[j]) < scores_diff)
            {
                double interArea = (testBox & refBoxes[j]).area();
                double iou = interArea / (testBox.area() + refBoxes[j].area() - interArea);
120
                topIoU = std::max(topIoU, iou);
121
                refBoxesIoUDiff[j] = std::min(refBoxesIoUDiff[j], 1.0f - iou);
122
                if (1.0 - iou < boxes_iou_diff)
123 124 125 126 127 128 129
                {
                    matched = true;
                    matchedRefBoxes[j] = true;
                }
            }
        }
        if (!matched)
130
        {
131 132
            std::cout << cv::format("Unmatched prediction: class %d score %f box ",
                                    testClassId, testScore) << testBox << std::endl;
133 134
            std::cout << "Highest IoU: " << topIoU << std::endl;
        }
135 136 137 138 139 140 141 142 143
        EXPECT_TRUE(matched) << comment;
    }

    // Check unmatched reference detections.
    for (int i = 0; i < refBoxes.size(); ++i)
    {
        if (!matchedRefBoxes[i] && refScores[i] > confThreshold)
        {
            std::cout << cv::format("Unmatched reference: class %d score %f box ",
144 145 146
                                    refClassIds[i], refScores[i]) << refBoxes[i]
                << " IoU diff: " << refBoxesIoUDiff[i]
                << std::endl;
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
            EXPECT_LE(refScores[i], confThreshold) << comment;
        }
    }
}

// For SSD-based object detection networks which produce output of shape 1x1xNx7
// where N is a number of detections and an every detection is represented by
// a vector [batchId, classId, confidence, left, top, right, bottom].
void normAssertDetections(
        cv::Mat ref, cv::Mat out, const char *comment /*= ""*/,
        double confThreshold /*= 0.0*/, double scores_diff /*= 1e-5*/,
        double boxes_iou_diff /*= 1e-4*/)
{
    CV_Assert(ref.total() % 7 == 0);
    CV_Assert(out.total() % 7 == 0);
    ref = ref.reshape(1, ref.total() / 7);
    out = out.reshape(1, out.total() / 7);

    cv::Mat refClassIds, testClassIds;
    ref.col(1).convertTo(refClassIds, CV_32SC1);
    out.col(1).convertTo(testClassIds, CV_32SC1);
    std::vector<float> refScores(ref.col(2)), testScores(out.col(2));
    std::vector<cv::Rect2d> refBoxes = matToBoxes(ref.colRange(3, 7));
    std::vector<cv::Rect2d> testBoxes = matToBoxes(out.colRange(3, 7));
    normAssertDetections(refClassIds, refScores, refBoxes, testClassIds, testScores,
                         testBoxes, comment, confThreshold, scores_diff, boxes_iou_diff);
}

175
void readFileContent(const std::string& filename, CV_OUT std::vector<char>& content)
176
{
177
    const std::ios::openmode mode = std::ios::in | std::ios::binary;
178
    std::ifstream ifs(filename.c_str(), mode);
179
    ASSERT_TRUE(ifs.is_open());
180 181 182 183

    content.clear();

    ifs.seekg(0, std::ios::end);
184 185
    const size_t sz = ifs.tellg();
    content.resize(sz);
186 187
    ifs.seekg(0, std::ios::beg);

188 189
    ifs.read((char*)content.data(), sz);
    ASSERT_FALSE(ifs.fail());
190 191 192 193 194 195
}


testing::internal::ParamGenerator< tuple<Backend, Target> > dnnBackendsAndTargets(
        bool withInferenceEngine /*= true*/,
        bool withHalide /*= false*/,
196 197
        bool withCpuOCV /*= true*/,
        bool withNgraph /*= true*/
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
)
{
#ifdef HAVE_INF_ENGINE
    bool withVPU = validateVPUType();
#endif

    std::vector< tuple<Backend, Target> > targets;
    std::vector< Target > available;
    if (withHalide)
    {
        available = getAvailableTargets(DNN_BACKEND_HALIDE);
        for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
            targets.push_back(make_tuple(DNN_BACKEND_HALIDE, *i));
    }
#ifdef HAVE_INF_ENGINE
    if (withInferenceEngine)
    {
215
        available = getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019);
216 217 218 219
        for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
        {
            if (*i == DNN_TARGET_MYRIAD && !withVPU)
                continue;
220
            targets.push_back(make_tuple(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, *i));
221 222
        }
    }
223 224 225 226 227 228 229 230 231 232 233
    if (withNgraph)
    {
        available = getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH);
        for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
        {
            if (*i == DNN_TARGET_MYRIAD && !withVPU)
                continue;
            targets.push_back(make_tuple(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, *i));
        }

    }
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
#else
    CV_UNUSED(withInferenceEngine);
#endif
    {
        available = getAvailableTargets(DNN_BACKEND_OPENCV);
        for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
        {
            if (!withCpuOCV && *i == DNN_TARGET_CPU)
                continue;
            targets.push_back(make_tuple(DNN_BACKEND_OPENCV, *i));
        }
    }
    if (targets.empty())  // validate at least CPU mode
        targets.push_back(make_tuple(DNN_BACKEND_OPENCV, DNN_TARGET_CPU));
    return testing::ValuesIn(targets);
}

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
testing::internal::ParamGenerator< tuple<Backend, Target> > dnnBackendsAndTargetsIE()
{
#ifdef HAVE_INF_ENGINE
    bool withVPU = validateVPUType();

    std::vector< tuple<Backend, Target> > targets;
    std::vector< Target > available;

    {
        available = getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019);
        for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
        {
            if (*i == DNN_TARGET_MYRIAD && !withVPU)
                continue;
            targets.push_back(make_tuple(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, *i));
        }
    }

    {
        available = getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH);
        for (std::vector< Target >::const_iterator i = available.begin(); i != available.end(); ++i)
        {
            if (*i == DNN_TARGET_MYRIAD && !withVPU)
                continue;
            targets.push_back(make_tuple(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, *i));
        }

    }

    return testing::ValuesIn(targets);
#else
    return testing::ValuesIn(std::vector< tuple<Backend, Target> >());
#endif
}
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

#ifdef HAVE_INF_ENGINE
static std::string getTestInferenceEngineVPUType()
{
    static std::string param_vpu_type = utils::getConfigurationParameterString("OPENCV_TEST_DNN_IE_VPU_TYPE", "");
    return param_vpu_type;
}

static bool validateVPUType_()
{
    std::string test_vpu_type = getTestInferenceEngineVPUType();
    if (test_vpu_type == "DISABLED" || test_vpu_type == "disabled")
    {
        return false;
    }

    std::vector<Target> available = getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE);
    bool have_vpu_target = false;
    for (std::vector<Target>::const_iterator i = available.begin(); i != available.end(); ++i)
    {
        if (*i == DNN_TARGET_MYRIAD)
        {
            have_vpu_target = true;
            break;
        }
    }

    if (test_vpu_type.empty())
    {
        if (have_vpu_target)
        {
            CV_LOG_INFO(NULL, "OpenCV-DNN-Test: VPU type for testing is not specified via 'OPENCV_TEST_DNN_IE_VPU_TYPE' parameter.")
        }
    }
    else
    {
        if (!have_vpu_target)
        {
            CV_LOG_FATAL(NULL, "OpenCV-DNN-Test: 'OPENCV_TEST_DNN_IE_VPU_TYPE' parameter requires VPU of type = '" << test_vpu_type << "', but VPU is not detected. STOP.");
            exit(1);
        }
        std::string dnn_vpu_type = getInferenceEngineVPUType();
        if (dnn_vpu_type != test_vpu_type)
        {
            CV_LOG_FATAL(NULL, "OpenCV-DNN-Test: 'testing' and 'detected' VPU types mismatch: '" << test_vpu_type << "' vs '" << dnn_vpu_type << "'. STOP.");
            exit(1);
        }
    }
333 334 335 336 337 338 339 340
    if (have_vpu_target)
    {
        std::string dnn_vpu_type = getInferenceEngineVPUType();
        if (dnn_vpu_type == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_2)
            registerGlobalSkipTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD_2);
        if (dnn_vpu_type == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X)
            registerGlobalSkipTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD_X);
    }
341 342 343 344 345 346 347 348 349 350
    return true;
}

bool validateVPUType()
{
    static bool result = validateVPUType_();
    return result;
}
#endif // HAVE_INF_ENGINE

351 352 353 354 355 356 357 358 359 360 361 362 363

void initDNNTests()
{
    const char* extraTestDataPath =
#ifdef WINRT
        NULL;
#else
        getenv("OPENCV_DNN_TEST_DATA_PATH");
#endif
    if (extraTestDataPath)
        cvtest::addDataSearchPath(extraTestDataPath);

    registerGlobalSkipTag(
364 365
        CV_TEST_TAG_DNN_SKIP_OPENCV_BACKEND,
        CV_TEST_TAG_DNN_SKIP_CPU,
366 367
        CV_TEST_TAG_DNN_SKIP_OPENCL, CV_TEST_TAG_DNN_SKIP_OPENCL_FP16
    );
368 369 370
#if defined(HAVE_HALIDE)
    registerGlobalSkipTag(
        CV_TEST_TAG_DNN_SKIP_HALIDE
371
    );
372
#endif
373 374
#if defined(INF_ENGINE_RELEASE)
    registerGlobalSkipTag(
375
        CV_TEST_TAG_DNN_SKIP_IE,
376 377 378 379
#if INF_ENGINE_VER_MAJOR_EQ(2018050000)
        CV_TEST_TAG_DNN_SKIP_IE_2018R5,
#elif INF_ENGINE_VER_MAJOR_EQ(2019010000)
        CV_TEST_TAG_DNN_SKIP_IE_2019R1,
A
Alexander Alekhin 已提交
380 381 382 383 384
# if INF_ENGINE_RELEASE == 2019010100
        CV_TEST_TAG_DNN_SKIP_IE_2019R1_1,
# endif
#elif INF_ENGINE_VER_MAJOR_EQ(2019020000)
        CV_TEST_TAG_DNN_SKIP_IE_2019R2,
A
Alexander Alekhin 已提交
385 386
#elif INF_ENGINE_VER_MAJOR_EQ(2019030000)
        CV_TEST_TAG_DNN_SKIP_IE_2019R3,
387
#endif
388 389 390
#ifdef HAVE_DNN_NGRAPH
        CV_TEST_TAG_DNN_SKIP_IE_NGRAPH,
#endif
391 392 393
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
        CV_TEST_TAG_DNN_SKIP_IE_NN_BUILDER,
#endif
394
        CV_TEST_TAG_DNN_SKIP_IE_CPU
395 396 397 398 399
    );
    registerGlobalSkipTag(
        // see validateVPUType(): CV_TEST_TAG_DNN_SKIP_IE_MYRIAD_2, CV_TEST_TAG_DNN_SKIP_IE_MYRIAD_X
        CV_TEST_TAG_DNN_SKIP_IE_OPENCL, CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16
    );
400
#endif
401 402 403 404
    registerGlobalSkipTag(
        CV_TEST_TAG_DNN_SKIP_ONNX_CONFORMANCE,
        CV_TEST_TAG_DNN_SKIP_PARSER
    );
405 406
}

407
} // namespace