openpose_python.cpp 26.5 KB
Newer Older
R
Raaj 已提交
1 2 3 4
#ifndef OPENPOSE_PYTHON_HPP
#define OPENPOSE_PYTHON_HPP
#define BOOST_DATE_TIME_NO_LIB

R
Raaj 已提交
5 6 7 8 9
#include <openpose/flags.hpp>
#include <openpose/headers.hpp>

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
10
#include <pybind11/stl_bind.h>
R
Raaj 已提交
11 12 13
#include <pybind11/numpy.h>
#include <opencv2/core/core.hpp>
#include <stdexcept>
R
Raaj 已提交
14

15 16
PYBIND11_MAKE_OPAQUE(std::vector<std::shared_ptr<op::Datum>>);

R
Raaj 已提交
17 18 19 20 21 22
#ifdef _WIN32
    #define OP_EXPORT __declspec(dllexport)
#else
    #define OP_EXPORT
#endif

G
Gines Hidalgo 已提交
23
namespace op
R
Raaj 已提交
24 25
{

G
Gines Hidalgo 已提交
26
    namespace py = pybind11;
R
Raaj 已提交
27

G
Gines Hidalgo 已提交
28
    void parse_gflags(const std::vector<std::string>& argv)
R
Raaj 已提交
29
    {
30 31
        try
        {
G
Gines Hidalgo 已提交
32 33 34 35 36 37
            std::vector<char*> argv_vec;
            for (auto& arg : argv)
                argv_vec.emplace_back((char*)arg.c_str());
            char** cast = &argv_vec[0];
            int size = (int)argv_vec.size();
            gflags::ParseCommandLineFlags(&size, &cast, true);
38 39 40 41 42
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
G
gineshidalgo99 已提交
43 44
    }

G
Gines Hidalgo 已提交
45
    void init_int(py::dict d)
46 47 48
    {
        try
        {
G
Gines Hidalgo 已提交
49 50 51 52 53 54 55 56 57 58 59 60
            std::vector<std::string> argv;
            argv.emplace_back("openpose.py");
            for (auto item : d){
                // Sanity check
                std::size_t found = std::string(py::str(item.first)).find("=");
                if (found != std::string::npos)
                    error("PyOpenPose does not support equal sign flags (e.g., "
                        + std::string(py::str(item.first)) + ").", __LINE__, __FUNCTION__, __FILE__);
                // Add argument
                argv.emplace_back("--" + std::string(py::str(item.first)) + "=" + std::string(py::str(item.second)));
            }
            parse_gflags(argv);
61 62 63 64 65
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
G
gineshidalgo99 已提交
66 67
    }

G
Gines Hidalgo 已提交
68
    void init_argv(std::vector<std::string> argv)
69 70 71
    {
        try
        {
G
Gines Hidalgo 已提交
72 73
            argv.insert(argv.begin(), "openpose.py");
            parse_gflags(argv);
74 75 76 77 78
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
G
gineshidalgo99 已提交
79 80
    }

G
Gines Hidalgo 已提交
81 82 83
    class WrapperPython{
    public:
        std::unique_ptr<Wrapper> opWrapper;
84
        bool synchronousIn;
G
Gines Hidalgo 已提交
85

86
        WrapperPython(ThreadManagerMode mode = ThreadManagerMode::Asynchronous)
87
        {
G
Gines Hidalgo 已提交
88 89 90
            opLog("Starting OpenPose Python Wrapper...", Priority::High);

            // Construct opWrapper
91 92 93 94 95 96 97
            opWrapper = std::unique_ptr<Wrapper>(new Wrapper(mode));

            // Synchronous in
            synchronousIn = (
                mode == ThreadManagerMode::AsynchronousOut ||
                mode == ThreadManagerMode::Synchronous
            );
98
        }
G
Gines Hidalgo 已提交
99 100

        void configure(py::dict params = py::dict())
101
        {
G
Gines Hidalgo 已提交
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
            try
            {
                if (params.size())
                    init_int(params);

                // logging_level
                checkBool(
                    0 <= FLAGS_logging_level && FLAGS_logging_level <= 255, "Wrong logging_level value.",
                    __LINE__, __FUNCTION__, __FILE__);
                ConfigureLog::setPriorityThreshold((Priority)FLAGS_logging_level);
                Profiler::setDefaultX(FLAGS_profile_speed);

                // Applying user defined configuration - GFlags to program variables
                // outputSize
                const auto outputSize = flagsToPoint(op::String(FLAGS_output_resolution), "-1x-1");
                // netInputSize
                const auto netInputSize = flagsToPoint(op::String(FLAGS_net_resolution), "-1x368");
                // faceNetInputSize
                const auto faceNetInputSize = flagsToPoint(op::String(FLAGS_face_net_resolution), "368x368 (multiples of 16)");
                // handNetInputSize
                const auto handNetInputSize = flagsToPoint(op::String(FLAGS_hand_net_resolution), "368x368 (multiples of 16)");
                // poseMode
                const auto poseMode = flagsToPoseMode(FLAGS_body);
                // poseModel
                const auto poseModel = flagsToPoseModel(op::String(FLAGS_model_pose));
                // JSON saving
                if (!FLAGS_write_keypoint.empty())
                    opLog("Flag `write_keypoint` is deprecated and will eventually be removed."
                            " Please, use `write_json` instead.", Priority::Max);
                // keypointScaleMode
                const auto keypointScaleMode = flagsToScaleMode(FLAGS_keypoint_scale);
                // heatmaps to add
                const auto heatMapTypes = flagsToHeatMaps(FLAGS_heatmaps_add_parts, FLAGS_heatmaps_add_bkg,
                                                              FLAGS_heatmaps_add_PAFs);
                const auto heatMapScaleMode = flagsToHeatMapScaleMode(FLAGS_heatmaps_scale);
                // >1 camera view?
                const auto multipleView = (FLAGS_3d || FLAGS_3d_views > 1);
                // Face and hand detectors
                const auto faceDetector = flagsToDetector(FLAGS_face_detector);
                const auto handDetector = flagsToDetector(FLAGS_hand_detector);
                // Enabling Google Logging
                const bool enableGoogleLogging = true;

                // Pose configuration (use WrapperStructPose{} for default and recommended configuration)
                const op::WrapperStructPose wrapperStructPose{
G
Gines Hidalgo 已提交
147 148 149 150 151 152 153
                    poseMode, netInputSize, FLAGS_net_resolution_dynamic, outputSize, keypointScaleMode, FLAGS_num_gpu,
                    FLAGS_num_gpu_start, FLAGS_scale_number, (float)FLAGS_scale_gap,
                    op::flagsToRenderMode(FLAGS_render_pose, multipleView), poseModel, !FLAGS_disable_blending,
                    (float)FLAGS_alpha_pose, (float)FLAGS_alpha_heatmap, FLAGS_part_to_show, op::String(FLAGS_model_folder),
                    heatMapTypes, heatMapScaleMode, FLAGS_part_candidates, (float)FLAGS_render_threshold,
                    FLAGS_number_people_max, FLAGS_maximize_positives, FLAGS_fps_max, op::String(FLAGS_prototxt_path),
                    op::String(FLAGS_caffemodel_path), (float)FLAGS_upsampling_ratio, enableGoogleLogging};
G
Gines Hidalgo 已提交
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
                opWrapper->configure(wrapperStructPose);
                // Face configuration (use WrapperStructFace{} to disable it)
                const WrapperStructFace wrapperStructFace{
                    FLAGS_face, faceDetector, faceNetInputSize,
                    flagsToRenderMode(FLAGS_face_render, multipleView, FLAGS_render_pose),
                    (float)FLAGS_face_alpha_pose, (float)FLAGS_face_alpha_heatmap, (float)FLAGS_face_render_threshold};
                opWrapper->configure(wrapperStructFace);
                // Hand configuration (use WrapperStructHand{} to disable it)
                const WrapperStructHand wrapperStructHand{
                    FLAGS_hand, handDetector, handNetInputSize, FLAGS_hand_scale_number, (float)FLAGS_hand_scale_range,
                    flagsToRenderMode(FLAGS_hand_render, multipleView, FLAGS_render_pose), (float)FLAGS_hand_alpha_pose,
                    (float)FLAGS_hand_alpha_heatmap, (float)FLAGS_hand_render_threshold};
                opWrapper->configure(wrapperStructHand);
                // Extra functionality configuration (use WrapperStructExtra{} to disable it)
                const WrapperStructExtra wrapperStructExtra{
                    FLAGS_3d, FLAGS_3d_min_views, FLAGS_identification, FLAGS_tracking, FLAGS_ik_threads};
                opWrapper->configure(wrapperStructExtra);
                // Output (comment or use default argument to disable any output)
                const WrapperStructOutput wrapperStructOutput{
                    FLAGS_cli_verbose, op::String(FLAGS_write_keypoint), op::stringToDataFormat(FLAGS_write_keypoint_format),
                    op::String(FLAGS_write_json), op::String(FLAGS_write_coco_json), FLAGS_write_coco_json_variants,
                    FLAGS_write_coco_json_variant, op::String(FLAGS_write_images), op::String(FLAGS_write_images_format),
                    op::String(FLAGS_write_video), FLAGS_write_video_fps, FLAGS_write_video_with_audio,
                    op::String(FLAGS_write_heatmaps), op::String(FLAGS_write_heatmaps_format), op::String(FLAGS_write_video_3d),
                    op::String(FLAGS_write_video_adam), op::String(FLAGS_write_bvh), op::String(FLAGS_udp_host),
                    op::String(FLAGS_udp_port)};
                opWrapper->configure(wrapperStructOutput);
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
                if (synchronousIn) {
                    // SynchronousIn => We need a producer

                    // Producer (use default to disable any input)
                    const auto cameraSize = flagsToPoint(op::String(FLAGS_camera_resolution), "-1x-1");
                    ProducerType producerType;
                    op::String producerString;
                    std::tie(producerType, producerString) = flagsToProducer(
                        op::String(FLAGS_image_dir), op::String(FLAGS_video), op::String(FLAGS_ip_camera), FLAGS_camera,
                        FLAGS_flir_camera, FLAGS_flir_camera_index);
                    const WrapperStructInput wrapperStructInput{
                        producerType, producerString, FLAGS_frame_first, FLAGS_frame_step, FLAGS_frame_last,
                        FLAGS_process_real_time, FLAGS_frame_flip, FLAGS_frame_rotate, FLAGS_frames_repeat,
                        cameraSize, op::String(FLAGS_camera_parameter_path), FLAGS_frame_undistort, FLAGS_3d_views};
                    opWrapper->configure(wrapperStructInput);
                }
G
Gines Hidalgo 已提交
197 198 199 200 201 202 203 204 205
                // No GUI. Equivalent to: opWrapper.configure(WrapperStructGui{});
                // Set to single-thread (for sequential processing and/or debugging and/or reducing latency)
                if (FLAGS_disable_multi_thread)
                    opWrapper->disableMultiThreading();
            }
            catch (const std::exception& e)
            {
                error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            }
206
        }
G
gineshidalgo99 已提交
207

G
Gines Hidalgo 已提交
208
        void start()
209
        {
G
Gines Hidalgo 已提交
210 211 212 213 214 215 216 217
            try
            {
                opWrapper->start();
            }
            catch (const std::exception& e)
            {
                error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            }
218
        }
G
Gines Hidalgo 已提交
219 220

        void stop()
221
        {
G
Gines Hidalgo 已提交
222 223 224 225 226 227 228 229
            try
            {
                opWrapper->stop();
            }
            catch (const std::exception& e)
            {
                error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            }
230
        }
R
Raaj 已提交
231

G
Gines Hidalgo 已提交
232
        void exec()
233
        {
G
Gines Hidalgo 已提交
234 235 236 237 238 239 240 241 242 243 244 245
            try
            {
                // GUI (comment or use default argument to disable any visual output)
                const WrapperStructGui wrapperStructGui{
                    flagsToDisplayMode(FLAGS_display, FLAGS_3d), !FLAGS_no_gui_verbose, FLAGS_fullscreen};
                opWrapper->configure(wrapperStructGui);
                opWrapper->exec();
            }
            catch (const std::exception& e)
            {
                error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            }
246
        }
G
Gines Hidalgo 已提交
247

248
        bool emplaceAndPop(std::vector<std::shared_ptr<Datum>>& l)
249
        {
G
Gines Hidalgo 已提交
250 251
            try
            {
252 253 254 255 256 257 258 259 260
                std::shared_ptr<std::vector<std::shared_ptr<Datum>>> datumsPtr(
                    &l,
                    [](std::vector<std::shared_ptr<Datum>>*){}
                );
                auto got = opWrapper->emplaceAndPop(datumsPtr);
                if (got && datumsPtr.get() != &l) {
                    l.swap(*datumsPtr);
                }
                return got;
G
Gines Hidalgo 已提交
261 262 263 264
            }
            catch (const std::exception& e)
            {
                error(e.what(), __LINE__, __FUNCTION__, __FILE__);
265
                return false;
G
Gines Hidalgo 已提交
266
            }
267
        }
R
Raaj 已提交
268

269
        bool waitAndEmplace(std::vector<std::shared_ptr<Datum>>& l)
G
Gines Hidalgo 已提交
270 271 272
        {
            try
            {
273 274
                std::shared_ptr<std::vector<std::shared_ptr<Datum>>> datumsPtr(&l);
                return opWrapper->waitAndEmplace(datumsPtr);
G
Gines Hidalgo 已提交
275 276 277 278
            }
            catch (const std::exception& e)
            {
                error(e.what(), __LINE__, __FUNCTION__, __FILE__);
279
                return false;
G
Gines Hidalgo 已提交
280 281 282 283 284 285 286
            }
        }

        bool waitAndPop(std::vector<std::shared_ptr<Datum>>& l)
        {
            try
            {
287 288 289 290 291 292
                std::shared_ptr<std::vector<std::shared_ptr<Datum>>> datumsPtr;
                auto got = opWrapper->waitAndPop(datumsPtr);
                if (got) {
                    l.swap(*datumsPtr);
                }
                return got;
G
Gines Hidalgo 已提交
293 294 295 296 297 298 299 300 301 302
            }
            catch (const std::exception& e)
            {
                error(e.what(), __LINE__, __FUNCTION__, __FILE__);
                return false;
            }
        }
    };

    std::vector<std::string> getImagesFromDirectory(const std::string& directoryPath)
R
Raaj 已提交
303
    {
304 305
        try
        {
G
Gines Hidalgo 已提交
306
            return getFilesOnDirectory(directoryPath, Extensions::Images);
307 308 309 310
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
G
Gines Hidalgo 已提交
311
            return {};
312
        }
R
Raaj 已提交
313
    }
R
Raaj 已提交
314

G
Gines Hidalgo 已提交
315 316 317 318 319 320 321 322
    PYBIND11_MODULE(pyopenpose, m) {

        // Functions for Init Params
        m.def("init_int", &init_int, "Init Function");
        m.def("init_argv", &init_argv, "Init Function");
        m.def("get_gpu_number", &getGpuNumber, "Get Total GPU");
        m.def("get_images_on_directory", &getImagesFromDirectory, "Get Images On Directory");

R
Raaj 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        // Pose Mapping
        // Code example in doc/output.md, section Keypoint Ordering in C++/Python
        m.def("getPoseBodyPartMapping", &getPoseBodyPartMapping, "getPoseBodyPartMapping");
        m.def("getPoseNumberBodyParts", &getPoseNumberBodyParts, "getPoseNumberBodyParts");
        m.def("getPosePartPairs", &getPosePartPairs, "getPosePartPairs");
        m.def("getPoseMapIndex", &getPoseMapIndex, "getPoseMapIndex");
        py::enum_<PoseModel>(m, "PoseModel", py::arithmetic())
                .value("BODY_25", PoseModel::BODY_25)
                .value("COCO_18", PoseModel::COCO_18)
                .value("MPI_15", PoseModel::MPI_15)
                .value("MPI_15_4", PoseModel::MPI_15_4)
                .value("BODY_25B", PoseModel::BODY_25B)
                .value("BODY_135", PoseModel::BODY_135)
                .export_values();

G
Gines Hidalgo 已提交
338 339 340
        // OpenposePython
        py::class_<WrapperPython>(m, "WrapperPython")
            .def(py::init<>())
341
            .def(py::init<ThreadManagerMode>())
G
Gines Hidalgo 已提交
342 343 344 345 346 347 348 349 350
            .def("configure", &WrapperPython::configure)
            .def("start", &WrapperPython::start)
            .def("stop", &WrapperPython::stop)
            .def("execute", &WrapperPython::exec)
            .def("emplaceAndPop", &WrapperPython::emplaceAndPop)
            .def("waitAndEmplace", &WrapperPython::waitAndEmplace)
            .def("waitAndPop", &WrapperPython::waitAndPop)
            ;

351 352 353 354 355 356 357 358
        // ThreadManagerMode
        py::enum_<ThreadManagerMode>(m, "ThreadManagerMode")
            .value("Asynchronous", ThreadManagerMode::Asynchronous)
            .value("AsynchronousIn", ThreadManagerMode::AsynchronousIn)
            .value("AsynchronousOut", ThreadManagerMode::AsynchronousOut)
            .value("Synchronous", ThreadManagerMode::Synchronous)
            ;

G
Gines Hidalgo 已提交
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
        // Datum Object
        py::class_<Datum, std::shared_ptr<Datum>>(m, "Datum")
            .def(py::init<>())
            .def_readwrite("id", &Datum::id)
            .def_readwrite("subId", &Datum::subId)
            .def_readwrite("subIdMax", &Datum::subIdMax)
            .def_readwrite("name", &Datum::name)
            .def_readwrite("frameNumber", &Datum::frameNumber)
            .def_readwrite("cvInputData", &Datum::cvInputData)
            .def_readwrite("inputNetData", &Datum::inputNetData)
            .def_readwrite("outputData", &Datum::outputData)
            .def_readwrite("cvOutputData", &Datum::cvOutputData)
            .def_readwrite("cvOutputData3D", &Datum::cvOutputData3D)
            .def_readwrite("poseKeypoints", &Datum::poseKeypoints)
            .def_readwrite("poseIds", &Datum::poseIds)
            .def_readwrite("poseScores", &Datum::poseScores)
            .def_readwrite("poseHeatMaps", &Datum::poseHeatMaps)
            .def_readwrite("poseCandidates", &Datum::poseCandidates)
            .def_readwrite("faceRectangles", &Datum::faceRectangles)
            .def_readwrite("faceKeypoints", &Datum::faceKeypoints)
            .def_readwrite("faceHeatMaps", &Datum::faceHeatMaps)
            .def_readwrite("handRectangles", &Datum::handRectangles)
            .def_readwrite("handKeypoints", &Datum::handKeypoints)
            .def_readwrite("handHeatMaps", &Datum::handHeatMaps)
            .def_readwrite("poseKeypoints3D", &Datum::poseKeypoints3D)
            .def_readwrite("faceKeypoints3D", &Datum::faceKeypoints3D)
            .def_readwrite("handKeypoints3D", &Datum::handKeypoints3D)
            .def_readwrite("cameraMatrix", &Datum::cameraMatrix)
            .def_readwrite("cameraExtrinsics", &Datum::cameraExtrinsics)
            .def_readwrite("cameraIntrinsics", &Datum::cameraIntrinsics)
            .def_readwrite("poseNetOutput", &Datum::poseNetOutput)
            .def_readwrite("scaleInputToNetInputs", &Datum::scaleInputToNetInputs)
            .def_readwrite("netInputSizes", &Datum::netInputSizes)
            .def_readwrite("scaleInputToOutput", &Datum::scaleInputToOutput)
            .def_readwrite("netOutputSize", &Datum::netOutputSize)
            .def_readwrite("scaleNetToOutput", &Datum::scaleNetToOutput)
            .def_readwrite("elementRendered", &Datum::elementRendered)
            ;

398 399
        py::bind_vector<std::vector<std::shared_ptr<Datum>>>(m, "VectorDatum");

G
Gines Hidalgo 已提交
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
        // Rectangle
        py::class_<Rectangle<float>>(m, "Rectangle")
            .def("__repr__", [](Rectangle<float> &a) { return a.toString(); })
            .def(py::init<>())
            .def(py::init<float, float, float, float>())
            .def_readwrite("x", &Rectangle<float>::x)
            .def_readwrite("y", &Rectangle<float>::y)
            .def_readwrite("width", &Rectangle<float>::width)
            .def_readwrite("height", &Rectangle<float>::height)
            ;

        // Point
        py::class_<Point<int>>(m, "Point")
            .def("__repr__", [](Point<int> &a) { return a.toString(); })
            .def(py::init<>())
            .def(py::init<int, int>())
            .def_readwrite("x", &Point<int>::x)
            .def_readwrite("y", &Point<int>::y)
            ;

        #ifdef VERSION_INFO
            m.attr("__version__") = VERSION_INFO;
        #else
            m.attr("__version__") = "dev";
        #endif
425
    }
R
Raaj 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438
}

// Numpy - op::Array<float> interop
namespace pybind11 { namespace detail {

template <> struct type_caster<op::Array<float>> {
    public:

        PYBIND11_TYPE_CASTER(op::Array<float>, _("numpy.ndarray"));

        // Cast numpy to op::Array<float>
        bool load(handle src, bool imp)
        {
439 440
            try
            {
G
Gines Hidalgo 已提交
441
                UNUSED(imp);
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
                // array b(src, true);
                array b = reinterpret_borrow<array>(src);
                buffer_info info = b.request();

                if (info.format != format_descriptor<float>::format())
                    op::error("op::Array only supports float32 now", __LINE__, __FUNCTION__, __FILE__);

                //std::vector<int> a(info.shape);
                std::vector<int> shape(std::begin(info.shape), std::end(info.shape));

                // No copy
                value = op::Array<float>(shape, (float*)info.ptr);
                // Copy
                //value = op::Array<float>(shape);
                //memcpy(value.getPtr(), info.ptr, value.getVolume()*sizeof(float));

                return true;
            }
            catch (const std::exception& e)
            {
                op::error(e.what(), __LINE__, __FUNCTION__, __FILE__);
                return {};
            }
G
gineshidalgo99 已提交
465
        }
R
Raaj 已提交
466 467 468 469

        // Cast op::Array<float> to numpy
        static handle cast(const op::Array<float> &m, return_value_policy, handle defval)
        {
G
Gines Hidalgo 已提交
470
            UNUSED(defval);
471 472 473
            if (m.getSize().size() == 0) {
                return none();
            }
R
Raaj 已提交
474 475 476 477 478 479 480 481 482
            std::string format = format_descriptor<float>::format();
            return array(buffer_info(
                m.getPseudoConstPtr(),/* Pointer to buffer */
                sizeof(float),        /* Size of one scalar */
                format,               /* Python struct-style format descriptor */
                m.getSize().size(),   /* Number of dimensions */
                m.getSize(),          /* Buffer dimensions */
                m.getStride()         /* Strides (in bytes) for each index */
                )).release();
G
gineshidalgo99 已提交
483
        }
R
Raaj 已提交
484 485 486 487

    };
}} // namespace pybind11::detail

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
// Numpy - op::Array<long long> interop
namespace pybind11 { namespace detail {

template <> struct type_caster<op::Array<long long>> {
    public:

        PYBIND11_TYPE_CASTER(op::Array<long long>, _("numpy.ndarray"));

        // Cast numpy to op::Array<long long>
        bool load(handle src, bool imp)
        {
            op::error("op::Array<long long> is read only now", __LINE__, __FUNCTION__, __FILE__);
            return false;
        }

        // Cast op::Array<long long> to numpy
        static handle cast(const op::Array<long long> &m, return_value_policy, handle defval)
        {
            UNUSED(defval);
            if (m.getSize().size() == 0) {
                return none();
            }
            std::string format = format_descriptor<long long>::format();
            return array(buffer_info(
                m.getPseudoConstPtr(),/* Pointer to buffer */
                sizeof(long long),    /* Size of one scalar */
                format,               /* Python struct-style format descriptor */
                m.getSize().size(),   /* Number of dimensions */
                m.getSize(),          /* Buffer dimensions */
                m.getStride()         /* Strides (in bytes) for each index */
                )).release();
        }

    };
}} // namespace pybind11::detail

G
Gines Hidalgo 已提交
524
// Numpy - op::Matrix interop
R
Raaj 已提交
525 526
namespace pybind11 { namespace detail {

G
Gines Hidalgo 已提交
527
template <> struct type_caster<op::Matrix> {
R
Raaj 已提交
528 529
    public:

G
Gines Hidalgo 已提交
530
        PYBIND11_TYPE_CASTER(op::Matrix, _("numpy.ndarray"));
R
Raaj 已提交
531

G
Gines Hidalgo 已提交
532
        // Cast numpy to op::Matrix
R
Raaj 已提交
533 534 535 536 537 538 539
        bool load(handle src, bool)
        {
            /* Try a default converting into a Python */
            //array b(src, true);
            array b = reinterpret_borrow<array>(src);
            buffer_info info = b.request();

G
Gines Hidalgo 已提交
540
            const int ndims = (int)info.ndim;
R
Raaj 已提交
541 542 543

            decltype(CV_32F) dtype;
            size_t elemsize;
G
Gines Hidalgo 已提交
544 545 546
            if (info.format == format_descriptor<float>::format())
            {
                if (ndims == 3)
R
Raaj 已提交
547
                    dtype = CV_32FC3;
G
Gines Hidalgo 已提交
548
                else
R
Raaj 已提交
549 550
                    dtype = CV_32FC1;
                elemsize = sizeof(float);
G
Gines Hidalgo 已提交
551 552 553 554
            }
            else if (info.format == format_descriptor<double>::format())
            {
                if (ndims == 3)
R
Raaj 已提交
555
                    dtype = CV_64FC3;
G
Gines Hidalgo 已提交
556
                else
R
Raaj 已提交
557 558
                    dtype = CV_64FC1;
                elemsize = sizeof(double);
G
Gines Hidalgo 已提交
559 560 561 562
            }
            else if (info.format == format_descriptor<unsigned char>::format())
            {
                if (ndims == 3)
R
Raaj 已提交
563
                    dtype = CV_8UC3;
G
Gines Hidalgo 已提交
564
                else
R
Raaj 已提交
565 566
                    dtype = CV_8UC1;
                elemsize = sizeof(unsigned char);
G
Gines Hidalgo 已提交
567 568 569
            }
            else
            {
R
Raaj 已提交
570 571
                throw std::logic_error("Unsupported type");
                return false;
G
gineshidalgo99 已提交
572 573
            }

R
Raaj 已提交
574
            std::vector<int> shape = {(int)info.shape[0], (int)info.shape[1]};
G
gineshidalgo99 已提交
575

G
Gines Hidalgo 已提交
576 577
            value = op::Matrix(shape[0], shape[1], dtype, info.ptr);
            // value = cv::Mat(cv::Size(shape[1], shape[0]), dtype, info.ptr, cv::Mat::AUTO_STEP);
R
Raaj 已提交
578
            return true;
G
gineshidalgo99 已提交
579
        }
R
Raaj 已提交
580

G
Gines Hidalgo 已提交
581 582
        // Cast op::Matrix to numpy
        static handle cast(const op::Matrix &matrix, return_value_policy, handle defval)
R
Raaj 已提交
583
        {
G
Gines Hidalgo 已提交
584
            UNUSED(defval);
R
Raaj 已提交
585 586 587
            std::string format = format_descriptor<unsigned char>::format();
            size_t elemsize = sizeof(unsigned char);
            int dim;
G
Gines Hidalgo 已提交
588
            switch(matrix.type()) {
R
Raaj 已提交
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
                case CV_8U:
                    format = format_descriptor<unsigned char>::format();
                    elemsize = sizeof(unsigned char);
                    dim = 2;
                    break;
                case CV_8UC3:
                    format = format_descriptor<unsigned char>::format();
                    elemsize = sizeof(unsigned char);
                    dim = 3;
                    break;
                case CV_32F:
                    format = format_descriptor<float>::format();
                    elemsize = sizeof(float);
                    dim = 2;
                    break;
                case CV_64F:
                    format = format_descriptor<double>::format();
                    elemsize = sizeof(double);
                    dim = 2;
                    break;
                default:
                    throw std::logic_error("Unsupported type");
            }

            std::vector<size_t> bufferdim;
            std::vector<size_t> strides;
            if (dim == 2) {
G
Gines Hidalgo 已提交
616 617
                bufferdim = {(size_t) matrix.rows(), (size_t) matrix.cols()};
                strides = {elemsize * (size_t) matrix.cols(), elemsize};
R
Raaj 已提交
618
            } else if (dim == 3) {
G
Gines Hidalgo 已提交
619 620
                bufferdim = {(size_t) matrix.rows(), (size_t) matrix.cols(), (size_t) 3};
                strides = {(size_t) elemsize * matrix.cols() * 3, (size_t) elemsize * 3, (size_t) elemsize};
R
Raaj 已提交
621 622
            }
            return array(buffer_info(
G
Gines Hidalgo 已提交
623 624 625 626 627 628
                matrix.dataPseudoConst(),   /* Pointer to buffer */
                elemsize,                   /* Size of one scalar */
                format,                     /* Python struct-style format descriptor */
                dim,                        /* Number of dimensions */
                bufferdim,                  /* Buffer dimensions */
                strides                     /* Strides (in bytes) for each index */
R
Raaj 已提交
629
                )).release();
G
gineshidalgo99 已提交
630
        }
R
Raaj 已提交
631

R
Raaj 已提交
632 633
    };
}} // namespace pybind11::detail
R
Raaj 已提交
634 635

#endif