mirror of
https://github.com/opencv/opencv.git
synced 2026-07-29 15:23:05 +04:00
Merge pull request #22037 from xiong-jie-y:py_gapi_add_state_kernel
Add stateful kernel to python G-API
This commit is contained in:
@@ -660,7 +660,8 @@ static cv::GRunArgs run_py_kernel(cv::detail::PyObjectHolder kernel,
|
||||
// NB: Doesn't increase reference counter (false),
|
||||
// because PyObject already have ownership.
|
||||
// In case exception decrement reference counter.
|
||||
cv::detail::PyObjectHolder args(PyTuple_New(ins.size()), false);
|
||||
cv::detail::PyObjectHolder args(
|
||||
PyTuple_New(ctx.m_state.has_value() ? ins.size() + 1 : ins.size()), false);
|
||||
for (size_t i = 0; i < ins.size(); ++i)
|
||||
{
|
||||
// NB: If meta is monostate then object isn't associated with G-TYPE.
|
||||
@@ -690,6 +691,12 @@ static cv::GRunArgs run_py_kernel(cv::detail::PyObjectHolder kernel,
|
||||
}
|
||||
++in_idx;
|
||||
}
|
||||
|
||||
if (ctx.m_state.has_value())
|
||||
{
|
||||
PyTuple_SetItem(args.get(), ins.size(), pyopencv_from(ctx.m_state.value()));
|
||||
}
|
||||
|
||||
// NB: Doesn't increase reference counter (false).
|
||||
// In case PyObject_CallObject return NULL, do nothing in destructor.
|
||||
cv::detail::PyObjectHolder result(
|
||||
@@ -736,6 +743,86 @@ static cv::GRunArgs run_py_kernel(cv::detail::PyObjectHolder kernel,
|
||||
return outs;
|
||||
}
|
||||
|
||||
static void unpackMetasToTuple(const cv::GMetaArgs& meta,
|
||||
const cv::GArgs& gargs,
|
||||
cv::detail::PyObjectHolder& tuple)
|
||||
{
|
||||
size_t idx = 0;
|
||||
for (auto&& m : meta)
|
||||
{
|
||||
switch (m.index())
|
||||
{
|
||||
case cv::GMetaArg::index_of<cv::GMatDesc>():
|
||||
PyTuple_SetItem(tuple.get(), idx, pyopencv_from(cv::util::get<cv::GMatDesc>(m)));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::GScalarDesc>():
|
||||
PyTuple_SetItem(tuple.get(), idx,
|
||||
pyopencv_from(cv::util::get<cv::GScalarDesc>(m)));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::GArrayDesc>():
|
||||
PyTuple_SetItem(tuple.get(), idx,
|
||||
pyopencv_from(cv::util::get<cv::GArrayDesc>(m)));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::GOpaqueDesc>():
|
||||
PyTuple_SetItem(tuple.get(), idx,
|
||||
pyopencv_from(cv::util::get<cv::GOpaqueDesc>(m)));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::util::monostate>():
|
||||
PyTuple_SetItem(tuple.get(), idx, pyopencv_from(gargs[idx]));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::GFrameDesc>():
|
||||
util::throw_error(
|
||||
std::logic_error("GFrame isn't supported for custom operation"));
|
||||
break;
|
||||
}
|
||||
++idx;
|
||||
}
|
||||
}
|
||||
|
||||
static cv::GArg setup_py(cv::detail::PyObjectHolder setup,
|
||||
const cv::GMetaArgs& meta,
|
||||
const cv::GArgs& gargs)
|
||||
{
|
||||
PyGILState_STATE gstate;
|
||||
gstate = PyGILState_Ensure();
|
||||
|
||||
cv::GArg out;
|
||||
|
||||
try
|
||||
{
|
||||
// NB: Doesn't increase reference counter (false),
|
||||
// because PyObject already have ownership.
|
||||
// In case exception decrement reference counter.
|
||||
cv::detail::PyObjectHolder args(PyTuple_New(meta.size()), false);
|
||||
unpackMetasToTuple(meta, gargs, args);
|
||||
// NB: Take an onwership because this state is "Python" type so it will be wrapped as-is
|
||||
// into cv::GArg and stored in GPythonBackend. Object without ownership can't
|
||||
// be dealocated outside this function.
|
||||
cv::detail::PyObjectHolder result(PyObject_CallObject(setup.get(), args.get()), true);
|
||||
|
||||
if (PyErr_Occurred())
|
||||
{
|
||||
PyErr_PrintEx(0);
|
||||
PyErr_Clear();
|
||||
throw std::logic_error("Python kernel failed with error!");
|
||||
}
|
||||
// NB: In fact it's impossible situation, because errors were handled above.
|
||||
GAPI_Assert(result.get() && "Python kernel returned NULL!");
|
||||
|
||||
if (!pyopencv_to(result.get(), out, ArgInfo("arg", false)))
|
||||
{
|
||||
util::throw_error(std::logic_error("Unsupported output meta type"));
|
||||
}
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
PyGILState_Release(gstate);
|
||||
throw;
|
||||
}
|
||||
PyGILState_Release(gstate);
|
||||
return out;
|
||||
}
|
||||
|
||||
static GMetaArg get_meta_arg(PyObject* obj)
|
||||
{
|
||||
cv::GMetaArg arg;
|
||||
@@ -761,8 +848,8 @@ static cv::GMetaArgs get_meta_args(PyObject* tuple)
|
||||
}
|
||||
|
||||
static GMetaArgs run_py_meta(cv::detail::PyObjectHolder out_meta,
|
||||
const cv::GMetaArgs &meta,
|
||||
const cv::GArgs &gargs)
|
||||
const cv::GMetaArgs &meta,
|
||||
const cv::GArgs &gargs)
|
||||
{
|
||||
PyGILState_STATE gstate;
|
||||
gstate = PyGILState_Ensure();
|
||||
@@ -774,32 +861,7 @@ static GMetaArgs run_py_meta(cv::detail::PyObjectHolder out_meta,
|
||||
// because PyObject already have ownership.
|
||||
// In case exception decrement reference counter.
|
||||
cv::detail::PyObjectHolder args(PyTuple_New(meta.size()), false);
|
||||
size_t idx = 0;
|
||||
for (auto&& m : meta)
|
||||
{
|
||||
switch (m.index())
|
||||
{
|
||||
case cv::GMetaArg::index_of<cv::GMatDesc>():
|
||||
PyTuple_SetItem(args.get(), idx, pyopencv_from(cv::util::get<cv::GMatDesc>(m)));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::GScalarDesc>():
|
||||
PyTuple_SetItem(args.get(), idx, pyopencv_from(cv::util::get<cv::GScalarDesc>(m)));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::GArrayDesc>():
|
||||
PyTuple_SetItem(args.get(), idx, pyopencv_from(cv::util::get<cv::GArrayDesc>(m)));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::GOpaqueDesc>():
|
||||
PyTuple_SetItem(args.get(), idx, pyopencv_from(cv::util::get<cv::GOpaqueDesc>(m)));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::util::monostate>():
|
||||
PyTuple_SetItem(args.get(), idx, pyopencv_from(gargs[idx]));
|
||||
break;
|
||||
case cv::GMetaArg::index_of<cv::GFrameDesc>():
|
||||
util::throw_error(std::logic_error("GFrame isn't supported for custom operation"));
|
||||
break;
|
||||
}
|
||||
++idx;
|
||||
}
|
||||
unpackMetasToTuple(meta, gargs, args);
|
||||
// NB: Doesn't increase reference counter (false).
|
||||
// In case PyObject_CallObject return NULL, do nothing in destructor.
|
||||
cv::detail::PyObjectHolder result(
|
||||
@@ -860,6 +922,10 @@ static PyObject* pyopencv_cv_gapi_kernels(PyObject* , PyObject* py_args, PyObjec
|
||||
"Python kernel should contain run, please use cv.gapi.kernel to define kernel");
|
||||
return NULL;
|
||||
}
|
||||
PyObject* setup = nullptr;
|
||||
if (PyObject_HasAttrString(user_kernel, "setup")) {
|
||||
setup = PyObject_GetAttrString(user_kernel, "setup");
|
||||
}
|
||||
|
||||
std::string id;
|
||||
if (!pyopencv_to(id_obj, id, ArgInfo("id", false)))
|
||||
@@ -869,10 +935,22 @@ static PyObject* pyopencv_cv_gapi_kernels(PyObject* , PyObject* py_args, PyObjec
|
||||
}
|
||||
|
||||
using namespace std::placeholders;
|
||||
gapi::python::GPythonFunctor f(id.c_str(),
|
||||
std::bind(run_py_meta , cv::detail::PyObjectHolder{out_meta}, _1, _2),
|
||||
std::bind(run_py_kernel, cv::detail::PyObjectHolder{run} , _1));
|
||||
pkg.include(f);
|
||||
|
||||
if (setup)
|
||||
{
|
||||
gapi::python::GPythonFunctor f(
|
||||
id.c_str(), std::bind(run_py_meta, cv::detail::PyObjectHolder{out_meta}, _1, _2),
|
||||
std::bind(run_py_kernel, cv::detail::PyObjectHolder{run}, _1),
|
||||
std::bind(setup_py, cv::detail::PyObjectHolder{setup}, _1, _2));
|
||||
pkg.include(f);
|
||||
}
|
||||
else
|
||||
{
|
||||
gapi::python::GPythonFunctor f(
|
||||
id.c_str(), std::bind(run_py_meta, cv::detail::PyObjectHolder{out_meta}, _1, _2),
|
||||
std::bind(run_py_kernel, cv::detail::PyObjectHolder{run}, _1));
|
||||
pkg.include(f);
|
||||
}
|
||||
}
|
||||
return pyopencv_from(pkg);
|
||||
}
|
||||
|
||||
@@ -432,7 +432,7 @@ try:
|
||||
with self.assertRaises(Exception): create_op([cv.GMat, int], [cv.GMat]).on(cv.GMat())
|
||||
|
||||
|
||||
def test_stateful_kernel(self):
|
||||
def test_state_in_class(self):
|
||||
@cv.gapi.op('custom.sum', in_types=[cv.GArray.Int], out_types=[cv.GOpaque.Int])
|
||||
class GSum:
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import numpy as np
|
||||
import cv2 as cv
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from tests_common import NewOpenCVTests
|
||||
|
||||
|
||||
try:
|
||||
|
||||
if sys.version_info[:2] < (3, 0):
|
||||
raise unittest.SkipTest('Python 2.x is not supported')
|
||||
|
||||
|
||||
class CounterState:
|
||||
def __init__(self):
|
||||
self.counter = 0
|
||||
|
||||
|
||||
@cv.gapi.op('stateful_counter',
|
||||
in_types=[cv.GOpaque.Int],
|
||||
out_types=[cv.GOpaque.Int])
|
||||
class GStatefulCounter:
|
||||
"""Accumulate state counter on every call"""
|
||||
|
||||
@staticmethod
|
||||
def outMeta(desc):
|
||||
return cv.empty_gopaque_desc()
|
||||
|
||||
|
||||
@cv.gapi.kernel(GStatefulCounter)
|
||||
class GStatefulCounterImpl:
|
||||
"""Implementation for GStatefulCounter operation."""
|
||||
|
||||
@staticmethod
|
||||
def setup(desc):
|
||||
return CounterState()
|
||||
|
||||
@staticmethod
|
||||
def run(value, state):
|
||||
state.counter += value
|
||||
return state.counter
|
||||
|
||||
|
||||
class gapi_sample_pipelines(NewOpenCVTests):
|
||||
def test_stateful_kernel_single_instance(self):
|
||||
g_in = cv.GOpaque.Int()
|
||||
g_out = GStatefulCounter.on(g_in)
|
||||
comp = cv.GComputation(cv.GIn(g_in), cv.GOut(g_out))
|
||||
pkg = cv.gapi.kernels(GStatefulCounterImpl)
|
||||
|
||||
nums = [i for i in range(10)]
|
||||
acc = 0
|
||||
for v in nums:
|
||||
acc = comp.apply(cv.gin(v), args=cv.gapi.compile_args(pkg))
|
||||
|
||||
self.assertEqual(sum(nums), acc)
|
||||
|
||||
|
||||
def test_stateful_kernel_multiple_instances(self):
|
||||
# NB: Every counter has his own independent state.
|
||||
g_in = cv.GOpaque.Int()
|
||||
g_out0 = GStatefulCounter.on(g_in)
|
||||
g_out1 = GStatefulCounter.on(g_in)
|
||||
comp = cv.GComputation(cv.GIn(g_in), cv.GOut(g_out0, g_out1))
|
||||
pkg = cv.gapi.kernels(GStatefulCounterImpl)
|
||||
|
||||
nums = [i for i in range(10)]
|
||||
acc0 = acc1 = 0
|
||||
for v in nums:
|
||||
acc0, acc1 = comp.apply(cv.gin(v), args=cv.gapi.compile_args(pkg))
|
||||
|
||||
ref = sum(nums)
|
||||
self.assertEqual(ref, acc0)
|
||||
self.assertEqual(ref, acc1)
|
||||
|
||||
|
||||
def test_stateful_throw_setup(self):
|
||||
@cv.gapi.kernel(GStatefulCounter)
|
||||
class GThrowStatefulCounterImpl:
|
||||
"""Implementation for GStatefulCounter operation
|
||||
that throw exception in setup method"""
|
||||
|
||||
@staticmethod
|
||||
def setup(desc):
|
||||
raise Exception('Throw from setup method')
|
||||
|
||||
@staticmethod
|
||||
def run(value, state):
|
||||
raise Exception('Unreachable')
|
||||
|
||||
g_in = cv.GOpaque.Int()
|
||||
g_out = GStatefulCounter.on(g_in)
|
||||
comp = cv.GComputation(cv.GIn(g_in), cv.GOut(g_out))
|
||||
pkg = cv.gapi.kernels(GThrowStatefulCounterImpl)
|
||||
|
||||
with self.assertRaises(Exception): comp.apply(cv.gin(42),
|
||||
args=cv.gapi.compile_args(pkg))
|
||||
|
||||
|
||||
def test_stateful_reset(self):
|
||||
g_in = cv.GOpaque.Int()
|
||||
g_out = GStatefulCounter.on(g_in)
|
||||
comp = cv.GComputation(cv.GIn(g_in), cv.GOut(g_out))
|
||||
pkg = cv.gapi.kernels(GStatefulCounterImpl)
|
||||
|
||||
cc = comp.compileStreaming(args=cv.gapi.compile_args(pkg))
|
||||
|
||||
cc.setSource(cv.gin(1))
|
||||
cc.start()
|
||||
for i in range(1, 10):
|
||||
_, actual = cc.pull()
|
||||
self.assertEqual(i, actual)
|
||||
cc.stop()
|
||||
|
||||
cc.setSource(cv.gin(2))
|
||||
cc.start()
|
||||
for i in range(2, 10, 2):
|
||||
_, actual = cc.pull()
|
||||
self.assertEqual(i, actual)
|
||||
cc.stop()
|
||||
|
||||
|
||||
except unittest.SkipTest as e:
|
||||
|
||||
message = str(e)
|
||||
|
||||
class TestSkip(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.skipTest('Skip tests: ' + message)
|
||||
|
||||
def test_skip():
|
||||
pass
|
||||
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
NewOpenCVTests.bootstrap()
|
||||
Reference in New Issue
Block a user