File: gapi_ocv_stateful_kernel_tests.cpp

package info (click to toggle)
opencv 4.10.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 282,092 kB
  • sloc: cpp: 1,178,079; xml: 682,621; python: 49,092; lisp: 31,150; java: 25,469; ansic: 11,039; javascript: 6,085; sh: 1,214; cs: 601; perl: 494; objc: 210; makefile: 173
file content (686 lines) | stat: -rw-r--r-- 22,558 bytes parent folder | download
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
// 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.
//
// Copyright (C) 2020-2022 Intel Corporation

#include "gapi_ocv_stateful_kernel_test_utils.hpp"
#include <opencv2/gapi/cpu/core.hpp>
#include <opencv2/gapi/streaming/cap.hpp>

#include <opencv2/core.hpp>
#include <opencv2/core/cvstd.hpp>
#ifdef HAVE_OPENCV_VIDEO
#include <opencv2/video.hpp>
#endif

#include <memory> // required by std::shared_ptr

namespace opencv_test
{
    struct BackSubStateParams
    {
        std::string method;
    };

    struct CountStateSetupsParams
    {
        std::shared_ptr<int> pSetupsCount;
    };
} // namespace opencv_test

namespace cv
{
    namespace detail
    {
        template<> struct CompileArgTag<opencv_test::BackSubStateParams>
        {
            static const char* tag()
            {
                return "org.opencv.test.background_substractor_state_params";
            }
        };

        template<> struct CompileArgTag<opencv_test::CountStateSetupsParams>
        {
            static const char* tag()
            {
                return "org.opencv.test.count_state_setups_params";
            }
        };
    } // namespace detail
} // namespace cv

namespace opencv_test
{
//TODO: test OT, Background Subtractor, Kalman with 3rd version of API
//----------------------------------------------- Simple tests ------------------------------------------------
namespace
{
    G_TYPED_KERNEL(GCountCalls, <cv::GOpaque<int>(GMat)>, "org.opencv.test.count_calls")
    {
        static GOpaqueDesc outMeta(GMatDesc /* in */) { return empty_gopaque_desc(); }
    };

    GAPI_OCV_KERNEL_ST(GOCVCountCalls, GCountCalls, int)
    {
        static void setup(const cv::GMatDesc &/* in */, std::shared_ptr<int> &state)
        {
            state.reset(new int{  });
        }

        static void run(const cv::Mat &/* in */, int &out, int& state)
        {
            out = ++state;
        }
    };

    G_TYPED_KERNEL(GIsStateUpToDate, <cv::GOpaque<bool>(GMat)>,
                   "org.opencv.test.is_state_up-to-date")
    {
        static GOpaqueDesc outMeta(GMatDesc /* in */) { return empty_gopaque_desc(); }
    };

    GAPI_OCV_KERNEL_ST(GOCVIsStateUpToDate, GIsStateUpToDate, cv::Size)
    {
        static void setup(const cv::GMatDesc &in, std::shared_ptr<cv::Size> &state)
        {
            state.reset(new cv::Size(in.size));
        }

        static void run(const cv::Mat &in , bool &out, cv::Size& state)
        {
            out = in.size() == state;
        }
    };

    G_TYPED_KERNEL(GStInvalidResize, <GMat(GMat,Size,double,double,int)>,
                   "org.opencv.test.st_invalid_resize")
    {
         static GMatDesc outMeta(GMatDesc in, Size, double, double, int) { return in; }
    };

    GAPI_OCV_KERNEL_ST(GOCVStInvalidResize, GStInvalidResize, int)
    {
        static void setup(const cv::GMatDesc, cv::Size, double, double, int,
                          std::shared_ptr<int> &/* state */)
        {  }

        static void run(const cv::Mat& in, cv::Size sz, double fx, double fy, int interp,
                        cv::Mat &out, int& /* state */)
        {
            cv::resize(in, out, sz, fx, fy, interp);
        }
    };

    G_TYPED_KERNEL(GBackSub, <GMat(GMat)>, "org.opencv.test.background_substractor")
    {
         static GMatDesc outMeta(GMatDesc in) { return in.withType(CV_8U, 1); }
    };
#ifdef HAVE_OPENCV_VIDEO
    GAPI_OCV_KERNEL_ST(GOCVBackSub, GBackSub, cv::BackgroundSubtractor)
    {
        static void setup(const cv::GMatDesc &/* desc */,
                          std::shared_ptr<BackgroundSubtractor> &state,
                          const cv::GCompileArgs &compileArgs)
        {
            auto sbParams = cv::gapi::getCompileArg<BackSubStateParams>(compileArgs)
                                .value_or(BackSubStateParams { });

            if (sbParams.method == "knn")
                state = createBackgroundSubtractorKNN();
            else if (sbParams.method == "mog2")
                state = createBackgroundSubtractorMOG2();

            GAPI_Assert(state);
        }

        static void run(const cv::Mat& in, cv::Mat &out, BackgroundSubtractor& state)
        {
            state.apply(in, out, -1);
        }
    };
#endif

    G_TYPED_KERNEL(GCountStateSetups, <cv::GOpaque<bool>(GMat)>,
                   "org.opencv.test.count_state_setups")
    {
        static GOpaqueDesc outMeta(GMatDesc /* in */) { return empty_gopaque_desc(); }
    };

    GAPI_OCV_KERNEL_ST(GOCVCountStateSetups, GCountStateSetups, int)
    {
        static void setup(const cv::GMatDesc &, std::shared_ptr<int> &,
                          const cv::GCompileArgs &compileArgs)
        {
            auto params = cv::gapi::getCompileArg<CountStateSetupsParams>(compileArgs)
                .value_or(CountStateSetupsParams { });
            if (params.pSetupsCount != nullptr) {
                (*params.pSetupsCount)++;
            }
        }

        static void run(const cv::Mat & , bool &out, int &)
        {
            out = true;
        }
    };
}

TEST(StatefulKernel, StateInitOnceInRegularMode)
{
    cv::GMat in;
    cv::GOpaque<bool> out = GCountStateSetups::on(in);
    cv::GComputation c(cv::GIn(in), cv::GOut(out));

    // Input mat:
    cv::Mat inputData(1080, 1920, CV_8UC1);
    cv::randu(inputData, cv::Scalar::all(1), cv::Scalar::all(128));

    // variable to update when state is initialized in the kernel
    CountStateSetupsParams params;
    params.pSetupsCount.reset(new int(0));

    // Testing for 100 frames
    bool result { };
    for (int i = 0; i < 100; ++i) {
        c.apply(cv::gin(inputData), cv::gout(result),
                cv::compile_args(cv::gapi::kernels<GOCVCountStateSetups>(), params));
        EXPECT_TRUE(result);
        EXPECT_TRUE(params.pSetupsCount != nullptr);
        EXPECT_EQ(1, *params.pSetupsCount);
    }
}

struct StateInitOnce : public ::testing::TestWithParam<bool>{};
TEST_P(StateInitOnce, StreamingCompiledWithMeta)
{
    bool compileWithMeta = GetParam();
    cv::GMat in;
    cv::GOpaque<bool> out = GCountStateSetups::on(in);
    cv::GComputation c(cv::GIn(in), cv::GOut(out));

    // Input mat:
    cv::Mat inputData(1080, 1920, CV_8UC1);
    cv::randu(inputData, cv::Scalar::all(1), cv::Scalar::all(128));

    // variable to update when state is initialized in the kernel
    CountStateSetupsParams params;
    params.pSetupsCount.reset(new int(0));

    // Compilation & testing
    auto ccomp = (compileWithMeta)
        ? c.compileStreaming(cv::descr_of(inputData),
              cv::compile_args(cv::gapi::kernels<GOCVCountStateSetups>(),
                               params))
        : c.compileStreaming(
              cv::compile_args(cv::gapi::kernels<GOCVCountStateSetups>(),
                               params));

    ccomp.setSource(cv::gin(inputData));

    ccomp.start();
    EXPECT_TRUE(ccomp.running());

    int counter { };
    bool result;
    // Process mat 100 times
    while (ccomp.pull(cv::gout(result)) && (counter++ < 100)) {
        EXPECT_TRUE(params.pSetupsCount != nullptr);
        EXPECT_EQ(1, *params.pSetupsCount);
    }

    ccomp.stop();
    EXPECT_FALSE(ccomp.running());
}

INSTANTIATE_TEST_CASE_P(StatefulKernel, StateInitOnce, ::testing::Bool());

TEST(StatefulKernel, StateIsMutableInRuntime)
{
    constexpr int expectedCallsCount = 10;

    cv::Mat dummyIn { 1, 1, CV_8UC1 };
    int actualCallsCount = 0;

    // Declaration of G-API expression
    GMat in;
    GOpaque<int> out = GCountCalls::on(in);
    cv::GComputation comp(cv::GIn(in), cv::GOut(out));

    const auto pkg = cv::gapi::kernels<GOCVCountCalls>();

    // Compilation of G-API expression
    auto callsCounter = comp.compile(cv::descr_of(dummyIn), cv::compile_args(pkg));

    // Simulating video stream: call GCompiled multiple times
    for (int i = 0; i < expectedCallsCount; i++)
    {
        callsCounter(cv::gin(dummyIn), cv::gout(actualCallsCount));
        EXPECT_EQ(i + 1, actualCallsCount);
    }

    // End of "video stream"
    EXPECT_EQ(expectedCallsCount, actualCallsCount);

    // User asks G-API to prepare for a new stream
    callsCounter.prepareForNewStream();
    callsCounter(cv::gin(dummyIn), cv::gout(actualCallsCount));
    EXPECT_EQ(1, actualCallsCount);

}

TEST(StateIsResetOnNewStream, RegularMode)
{
    cv::GMat in;
    cv::GOpaque<bool> out = GCountStateSetups::on(in);
    cv::GComputation c(cv::GIn(in), cv::GOut(out));

    // Input mat:
    cv::Mat inputData(1080, 1920, CV_8UC1);
    cv::randu(inputData, cv::Scalar::all(1), cv::Scalar::all(128));

    // variable to update when state is initialized in the kernel
    CountStateSetupsParams params;
    params.pSetupsCount.reset(new int(0));

    auto setupsCounter = c.compile(cv::descr_of(inputData),
                                   cv::compile_args(cv::gapi::kernels<GOCVCountStateSetups>(),
                                                    params));

    bool result { };
    for (int i = 0; i < 2; ++i) {
        setupsCounter(cv::gin(inputData), cv::gout(result));
        EXPECT_TRUE(params.pSetupsCount != nullptr);
        EXPECT_EQ(1, *params.pSetupsCount);
    }

    EXPECT_TRUE(params.pSetupsCount != nullptr);
    EXPECT_EQ(1, *params.pSetupsCount);
    setupsCounter.prepareForNewStream();

    for (int i = 0; i < 2; ++i) {
        setupsCounter(cv::gin(inputData), cv::gout(result));
        EXPECT_TRUE(params.pSetupsCount != nullptr);
        EXPECT_EQ(2, *params.pSetupsCount);
    }
}

TEST(StateIsResetOnNewStream, StreamingMode)
{
    cv::GMat in;
    cv::GOpaque<bool> out = GIsStateUpToDate::on(in);
    cv::GComputation c(cv::GIn(in), cv::GOut(out));

    const auto pkg = cv::gapi::kernels<GOCVIsStateUpToDate>();

    // Compilation & testing
    auto ccomp = c.compileStreaming(cv::compile_args(pkg));

    auto path = findDataFile("cv/video/768x576.avi");
    try {
        ccomp.setSource(gapi::wip::make_src<cv::gapi::wip::GCaptureSource>(path));
    } catch(...) {
        throw SkipTestException("Video file can not be opened");
    }
    ccomp.start();
    EXPECT_TRUE(ccomp.running());

    // Process the full video
    bool isStateUpToDate = false;
    while (ccomp.pull(cv::gout(isStateUpToDate))) {
        EXPECT_TRUE(isStateUpToDate);
    }
    EXPECT_FALSE(ccomp.running());

    path = findDataFile("cv/video/1920x1080.avi");
    try {
        ccomp.setSource(gapi::wip::make_src<cv::gapi::wip::GCaptureSource>(path));
    } catch(...) {
        throw SkipTestException("Video file can not be opened");
    }
    ccomp.start();
    EXPECT_TRUE(ccomp.running());

    while (ccomp.pull(cv::gout(isStateUpToDate))) {
        EXPECT_TRUE(isStateUpToDate);
    }
    EXPECT_FALSE(ccomp.running());
}

TEST(StatefulKernel, InvalidReallocatingKernel)
{
    cv::GMat in, out;
    cv::Mat in_mat(500, 500, CV_8UC1), out_mat;
    out = GStInvalidResize::on(in, cv::Size(300, 300), 0.0, 0.0, cv::INTER_LINEAR);

    const auto pkg = cv::gapi::kernels<GOCVStInvalidResize>();
    cv::GComputation comp(cv::GIn(in), cv::GOut(out));

    EXPECT_THROW(comp.apply(in_mat, out_mat, cv::compile_args(pkg)), std::logic_error);
}

#ifdef HAVE_OPENCV_VIDEO
namespace
{
    void compareBackSubResults(const cv::Mat &actual, const cv::Mat &expected,
                               const int diffPercent)
    {
        GAPI_Assert(actual.size() == expected.size());
        int allowedNumDiffPixels = actual.size().area() * diffPercent / 100;

        cv::Mat diff;
        cv::absdiff(actual, expected, diff);

        cv::Mat hist(256, 1, CV_32FC1, cv::Scalar(0));
        const float range[] { 0, 256 };
        const float *histRange { range };
        calcHist(&diff, 1, 0, Mat(), hist, 1, &hist.rows, &histRange, true, false);
        for (int i = 2; i < hist.rows; ++i)
        {
            hist.at<float>(i) += hist.at<float>(i - 1);
        }

        int numDiffPixels = static_cast<int>(hist.at<float>(255));

        EXPECT_GT(allowedNumDiffPixels, numDiffPixels);
    }
} // anonymous namespace

TEST(StatefulKernel, StateIsInitViaCompArgs)
{
    cv::Mat frame(1080, 1920, CV_8UC3),
            gapiForeground,
            ocvForeground;

    cv::randu(frame, cv::Scalar(0, 0, 0), cv::Scalar(255, 255, 255));

    // G-API code
    cv::GMat in;
    cv::GMat out = GBackSub::on(in);
    cv::GComputation c(cv::GIn(in), cv::GOut(out));

    const auto pkg = cv::gapi::kernels<GOCVBackSub>();

    auto gapiBackSub = c.compile(cv::descr_of(frame),
                                 cv::compile_args(pkg, BackSubStateParams { "knn" }));

    gapiBackSub(cv::gin(frame), cv::gout(gapiForeground));

    // OpenCV code
    auto pOcvBackSub = createBackgroundSubtractorKNN();
    pOcvBackSub->apply(frame, ocvForeground);

    // Comparison
    // Allowing 1% difference of all pixels between G-API and OpenCV results
    compareBackSubResults(gapiForeground, ocvForeground, 1);

    // Additionally, test the case where state is reset
    gapiBackSub.prepareForNewStream();
    gapiBackSub(cv::gin(frame), cv::gout(gapiForeground));
    pOcvBackSub->apply(frame, ocvForeground);
    compareBackSubResults(gapiForeground, ocvForeground, 1);
}
#endif

#ifdef HAVE_OPENCV_VIDEO
namespace
{
    void testBackSubInStreaming(cv::GStreamingCompiled gapiBackSub, const int diffPercent)
    {
        cv::Mat frame,
                gapiForeground,
                ocvForeground;

        gapiBackSub.start();
        EXPECT_TRUE(gapiBackSub.running());

        // OpenCV reference substractor
        auto pOCVBackSub = createBackgroundSubtractorKNN();

        // Comparison of G-API and OpenCV substractors
        std::size_t frames = 0u;
        while (gapiBackSub.pull(cv::gout(frame, gapiForeground))) {
            pOCVBackSub->apply(frame, ocvForeground, -1);

            compareBackSubResults(gapiForeground, ocvForeground, diffPercent);

            frames++;
        }
        EXPECT_LT(0u, frames);
        EXPECT_FALSE(gapiBackSub.running());
    }
} // anonymous namespace

TEST(StatefulKernel, StateIsInitViaCompArgsInStreaming)
{
    // This test is long as it runs BG subtractor (a) twice
    // (in G-API + for reference) over (b) two files. In fact
    // it is one more BG Subtractor accuracy test, but not
    // a stateful initialization test -- the latter must be
    // done through a light-weight mock object. So for now:
    applyTestTag(CV_TEST_TAG_VERYLONG);

    // G-API graph declaration
    cv::GMat in;
    cv::GMat out = GBackSub::on(in);
    // Preserving 'in' in output to have possibility to compare with OpenCV reference
    cv::GComputation c(cv::GIn(in), cv::GOut(cv::gapi::copy(in), out));

    // G-API compilation of graph for streaming mode
    const auto pkg = cv::gapi::kernels<GOCVBackSub>();
    auto gapiBackSub = c.compileStreaming(
                           cv::compile_args(pkg, BackSubStateParams { "knn" }));

    // Testing G-API Background Substractor in streaming mode
    auto path = findDataFile("cv/video/768x576.avi");
    try {
        gapiBackSub.setSource(gapi::wip::make_src<cv::gapi::wip::GCaptureSource>(path));
    } catch(...) {
        throw SkipTestException("Video file can not be opened");
    }
    // Allowing 1% difference of all pixels between G-API and reference OpenCV results
    testBackSubInStreaming(gapiBackSub, 1);

    path = findDataFile("cv/video/1920x1080.avi");
    try {
        // Additionally, test the case when the new stream happens
        gapiBackSub.setSource(gapi::wip::make_src<cv::gapi::wip::GCaptureSource>(path));
    } catch(...) {
        throw SkipTestException("Video file can not be opened");
    }
    // Allowing 5% difference of all pixels between G-API and reference OpenCV results
    testBackSubInStreaming(gapiBackSub, 5);
}

TEST(StatefulKernel, StateIsChangedViaCompArgsOnReshape)
{
    cv::GMat in;
    cv::GComputation comp(in, GBackSub::on(in));

    const auto pkg = cv::gapi::kernels<GOCVBackSub>();

    // OpenCV reference substractor
    auto pOCVBackSubKNN = createBackgroundSubtractorKNN();
    auto pOCVBackSubMOG2 = createBackgroundSubtractorMOG2();

    const auto run = [&](const std::string& videoPath, const std::string& method) {
        auto path = findDataFile(videoPath);
        cv::gapi::wip::IStreamSource::Ptr source;
        try {
            source = gapi::wip::make_src<cv::gapi::wip::GCaptureSource>(path);
        } catch(...) {
            throw SkipTestException("Video file can not be opened");
        }
        cv::Mat inMat, gapiForeground, ocvForeground;

        for (int i = 0; i < 10; i++) {
            cv::gapi::wip::Data inData;
            source->pull(inData);
            inMat = cv::util::get<cv::Mat>(inData);
            comp.apply(inMat, gapiForeground,
                       cv::compile_args(pkg, BackSubStateParams{method}));

            if (method == "knn") {
                pOCVBackSubKNN->apply(inMat, ocvForeground, -1);
                // Allowing 1% difference among all pixels
                compareBackSubResults(gapiForeground, ocvForeground, 1);
            } else if (method == "mog2") {
                pOCVBackSubMOG2->apply(inMat, ocvForeground, -1);
                compareBackSubResults(gapiForeground, ocvForeground, 5);
            } else {
                CV_Assert(false && "Unknown BackSub method");
            }
        }
    };

    run("cv/video/768x576.avi", "knn");
    run("cv/video/1920x1080.avi", "mog2");
}

TEST(StatefulKernel, StateIsResetOnceOnReshapeInStreaming)
{
    cv::GMat in;
    cv::GOpaque<bool> out = GCountStateSetups::on(in);
    cv::GComputation c(cv::GIn(in), cv::GOut(out));

    // variable to update when state is initialized in the kernel
    CountStateSetupsParams params;
    params.pSetupsCount.reset(new int(0));

    auto ccomp = c.compileStreaming(
        cv::compile_args(cv::gapi::kernels<GOCVCountStateSetups>(), params));

    auto run = [&ccomp, &params](const std::string& videoPath, int expectedSetupsCount) {
        auto path = findDataFile(videoPath);
        try {
            ccomp.setSource<cv::gapi::wip::GCaptureSource>(path);
        } catch(...) {
            throw SkipTestException("Video file can not be opened");
        }
        ccomp.start();

        int frames = 0;
        bool result = false;
        while (ccomp.pull(cv::gout(result)) && (frames++ < 10)) {
            EXPECT_TRUE(result);
            EXPECT_TRUE(params.pSetupsCount != nullptr);
            EXPECT_EQ(expectedSetupsCount, *params.pSetupsCount);
        }
        ccomp.stop();
    };

    run("cv/video/768x576.avi", 1);
    // FIXME: it should be 2, not 3 for expectedSetupsCount here.
    // With current implemention both GCPUExecutable reshape() and
    // handleNewStream() call setupKernelStates()
    run("cv/video/1920x1080.avi", 3);
}
#endif

TEST(StatefulKernel, StateIsAutoResetOnReshape)
{
    cv::GMat in;
    cv::GOpaque<bool> up_to_date = GIsStateUpToDate::on(in);
    cv::GOpaque<int>  calls_count = GCountCalls::on(in);
    cv::GComputation comp(cv::GIn(in), cv::GOut(up_to_date, calls_count));

    auto run = [&comp](const cv::Mat& in_mat) {
        const auto pkg = cv::gapi::kernels<GOCVIsStateUpToDate, GOCVCountCalls>();
        bool stateIsUpToDate = false;
        int callsCount = 0;
        for (int i = 0; i < 3; i++) {
            comp.apply(cv::gin(in_mat), cv::gout(stateIsUpToDate, callsCount),
                       cv::compile_args(pkg));
            EXPECT_TRUE(stateIsUpToDate);
            EXPECT_EQ(i+1, callsCount);
        }
    };

    cv::Mat in_mat1(32, 32, CV_8UC1);
    run(in_mat1);

    cv::Mat in_mat2(16, 16, CV_8UC1);
    run(in_mat2);
}

//-------------------------------------------------------------------------------------------------------------


//------------------------------------------- Typed tests on setup() ------------------------------------------
namespace
{
template<typename Tuple>
struct SetupStateTypedTest : public ::testing::Test
{
    using StateT = typename std::tuple_element<0, Tuple>::type;
    using SetupT = typename std::tuple_element<1, Tuple>::type;

    G_TYPED_KERNEL(GReturnState, <cv::GOpaque<StateT>(GMat)>, "org.opencv.test.return_state")
    {
        static GOpaqueDesc outMeta(GMatDesc /* in */) { return empty_gopaque_desc(); }
    };

    GAPI_OCV_KERNEL_ST(GOCVReturnState, GReturnState, StateT)
    {
        static void setup(const cv::GMatDesc &/* in */, std::shared_ptr<StateT> &state)
        {
            // Don't use input cv::GMatDesc intentionally
            state.reset(new StateT(SetupT::value()));
        }

        static void run(const cv::Mat &/* in */, StateT &out, StateT& state)
        {
            out = state;
        }
    };
};

TYPED_TEST_CASE_P(SetupStateTypedTest);
} // namespace


TYPED_TEST_P(SetupStateTypedTest, ReturnInitializedState)
{
    using StateType = typename TestFixture::StateT;
    using SetupType = typename TestFixture::SetupT;

    cv::Mat dummyIn { 1, 1, CV_8UC1 };
    StateType retState { };

    GMat in;
    auto out = TestFixture::GReturnState::on(in);
    cv::GComputation comp(cv::GIn(in), cv::GOut(out));

    const auto pkg = cv::gapi::kernels<typename TestFixture::GOCVReturnState>();
    comp.apply(cv::gin(dummyIn), cv::gout(retState), cv::compile_args(pkg));

    EXPECT_EQ(SetupType::value(), retState);
}

REGISTER_TYPED_TEST_CASE_P(SetupStateTypedTest,
                           ReturnInitializedState);


DEFINE_INITIALIZER(CharValue, char, 'z');
DEFINE_INITIALIZER(IntValue, int, 7);
DEFINE_INITIALIZER(FloatValue, float, 42.f);
DEFINE_INITIALIZER(UcharPtrValue, uchar*, nullptr);
namespace
{
using Std3IntArray = std::array<int, 3>;
}
DEFINE_INITIALIZER(StdArrayValue, Std3IntArray, { 1, 2, 3 });
DEFINE_INITIALIZER(UserValue, UserStruct, { 5, 7.f });

using TypesToVerify = ::testing::Types<std::tuple<char, CharValue>,
                                       std::tuple<int, IntValue>,
                                       std::tuple<float, FloatValue>,
                                       std::tuple<uchar*, UcharPtrValue>,
                                       std::tuple<std::array<int, 3>, StdArrayValue>,
                                       std::tuple<UserStruct, UserValue>>;

INSTANTIATE_TYPED_TEST_CASE_P(SetupStateTypedInst, SetupStateTypedTest, TypesToVerify);
//-------------------------------------------------------------------------------------------------------------

} // opencv_test