Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

openpose_python.cpp 24 KB

You have to be logged in to leave a comment. Sign In
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
  1. #ifndef OPENPOSE_PYTHON_HPP
  2. #define OPENPOSE_PYTHON_HPP
  3. #define BOOST_DATE_TIME_NO_LIB
  4. #include <openpose/flags.hpp>
  5. #include <openpose/headers.hpp>
  6. #include <pybind11/pybind11.h>
  7. #include <pybind11/stl.h>
  8. #include <pybind11/numpy.h>
  9. #include <opencv2/core/core.hpp>
  10. #include <stdexcept>
  11. #ifdef _WIN32
  12. #define OP_EXPORT __declspec(dllexport)
  13. #else
  14. #define OP_EXPORT
  15. #endif
  16. namespace op
  17. {
  18. namespace py = pybind11;
  19. void parse_gflags(const std::vector<std::string>& argv)
  20. {
  21. try
  22. {
  23. std::vector<char*> argv_vec;
  24. for (auto& arg : argv)
  25. argv_vec.emplace_back((char*)arg.c_str());
  26. char** cast = &argv_vec[0];
  27. int size = (int)argv_vec.size();
  28. gflags::ParseCommandLineFlags(&size, &cast, true);
  29. }
  30. catch (const std::exception& e)
  31. {
  32. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  33. }
  34. }
  35. void init_int(py::dict d)
  36. {
  37. try
  38. {
  39. std::vector<std::string> argv;
  40. argv.emplace_back("openpose.py");
  41. for (auto item : d){
  42. // Sanity check
  43. std::size_t found = std::string(py::str(item.first)).find("=");
  44. if (found != std::string::npos)
  45. error("PyOpenPose does not support equal sign flags (e.g., "
  46. + std::string(py::str(item.first)) + ").", __LINE__, __FUNCTION__, __FILE__);
  47. // Add argument
  48. argv.emplace_back("--" + std::string(py::str(item.first)) + "=" + std::string(py::str(item.second)));
  49. }
  50. parse_gflags(argv);
  51. }
  52. catch (const std::exception& e)
  53. {
  54. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  55. }
  56. }
  57. void init_argv(std::vector<std::string> argv)
  58. {
  59. try
  60. {
  61. argv.insert(argv.begin(), "openpose.py");
  62. parse_gflags(argv);
  63. }
  64. catch (const std::exception& e)
  65. {
  66. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  67. }
  68. }
  69. class WrapperPython{
  70. public:
  71. std::unique_ptr<Wrapper> opWrapper;
  72. WrapperPython(int mode = 0)
  73. {
  74. opLog("Starting OpenPose Python Wrapper...", Priority::High);
  75. // Construct opWrapper
  76. opWrapper = std::unique_ptr<Wrapper>(new Wrapper(static_cast<ThreadManagerMode>(mode)));
  77. }
  78. void configure(py::dict params = py::dict())
  79. {
  80. try
  81. {
  82. if (params.size())
  83. init_int(params);
  84. // logging_level
  85. checkBool(
  86. 0 <= FLAGS_logging_level && FLAGS_logging_level <= 255, "Wrong logging_level value.",
  87. __LINE__, __FUNCTION__, __FILE__);
  88. ConfigureLog::setPriorityThreshold((Priority)FLAGS_logging_level);
  89. Profiler::setDefaultX(FLAGS_profile_speed);
  90. // Applying user defined configuration - GFlags to program variables
  91. // outputSize
  92. const auto outputSize = flagsToPoint(op::String(FLAGS_output_resolution), "-1x-1");
  93. // netInputSize
  94. const auto netInputSize = flagsToPoint(op::String(FLAGS_net_resolution), "-1x368");
  95. // faceNetInputSize
  96. const auto faceNetInputSize = flagsToPoint(op::String(FLAGS_face_net_resolution), "368x368 (multiples of 16)");
  97. // handNetInputSize
  98. const auto handNetInputSize = flagsToPoint(op::String(FLAGS_hand_net_resolution), "368x368 (multiples of 16)");
  99. // poseMode
  100. const auto poseMode = flagsToPoseMode(FLAGS_body);
  101. // poseModel
  102. const auto poseModel = flagsToPoseModel(op::String(FLAGS_model_pose));
  103. // JSON saving
  104. if (!FLAGS_write_keypoint.empty())
  105. opLog("Flag `write_keypoint` is deprecated and will eventually be removed."
  106. " Please, use `write_json` instead.", Priority::Max);
  107. // keypointScaleMode
  108. const auto keypointScaleMode = flagsToScaleMode(FLAGS_keypoint_scale);
  109. // heatmaps to add
  110. const auto heatMapTypes = flagsToHeatMaps(FLAGS_heatmaps_add_parts, FLAGS_heatmaps_add_bkg,
  111. FLAGS_heatmaps_add_PAFs);
  112. const auto heatMapScaleMode = flagsToHeatMapScaleMode(FLAGS_heatmaps_scale);
  113. // >1 camera view?
  114. const auto multipleView = (FLAGS_3d || FLAGS_3d_views > 1);
  115. // Face and hand detectors
  116. const auto faceDetector = flagsToDetector(FLAGS_face_detector);
  117. const auto handDetector = flagsToDetector(FLAGS_hand_detector);
  118. // Enabling Google Logging
  119. const bool enableGoogleLogging = true;
  120. // Pose configuration (use WrapperStructPose{} for default and recommended configuration)
  121. const op::WrapperStructPose wrapperStructPose{
  122. poseMode, netInputSize, outputSize, keypointScaleMode, FLAGS_num_gpu, FLAGS_num_gpu_start,
  123. FLAGS_scale_number, (float)FLAGS_scale_gap, op::flagsToRenderMode(FLAGS_render_pose, multipleView),
  124. poseModel, !FLAGS_disable_blending, (float)FLAGS_alpha_pose, (float)FLAGS_alpha_heatmap,
  125. FLAGS_part_to_show, op::String(FLAGS_model_folder), heatMapTypes, heatMapScaleMode, FLAGS_part_candidates,
  126. (float)FLAGS_render_threshold, FLAGS_number_people_max, FLAGS_maximize_positives, FLAGS_fps_max,
  127. op::String(FLAGS_prototxt_path), op::String(FLAGS_caffemodel_path),
  128. (float)FLAGS_upsampling_ratio, enableGoogleLogging};
  129. opWrapper->configure(wrapperStructPose);
  130. // Face configuration (use WrapperStructFace{} to disable it)
  131. const WrapperStructFace wrapperStructFace{
  132. FLAGS_face, faceDetector, faceNetInputSize,
  133. flagsToRenderMode(FLAGS_face_render, multipleView, FLAGS_render_pose),
  134. (float)FLAGS_face_alpha_pose, (float)FLAGS_face_alpha_heatmap, (float)FLAGS_face_render_threshold};
  135. opWrapper->configure(wrapperStructFace);
  136. // Hand configuration (use WrapperStructHand{} to disable it)
  137. const WrapperStructHand wrapperStructHand{
  138. FLAGS_hand, handDetector, handNetInputSize, FLAGS_hand_scale_number, (float)FLAGS_hand_scale_range,
  139. flagsToRenderMode(FLAGS_hand_render, multipleView, FLAGS_render_pose), (float)FLAGS_hand_alpha_pose,
  140. (float)FLAGS_hand_alpha_heatmap, (float)FLAGS_hand_render_threshold};
  141. opWrapper->configure(wrapperStructHand);
  142. // Extra functionality configuration (use WrapperStructExtra{} to disable it)
  143. const WrapperStructExtra wrapperStructExtra{
  144. FLAGS_3d, FLAGS_3d_min_views, FLAGS_identification, FLAGS_tracking, FLAGS_ik_threads};
  145. opWrapper->configure(wrapperStructExtra);
  146. // Output (comment or use default argument to disable any output)
  147. const WrapperStructOutput wrapperStructOutput{
  148. FLAGS_cli_verbose, op::String(FLAGS_write_keypoint), op::stringToDataFormat(FLAGS_write_keypoint_format),
  149. op::String(FLAGS_write_json), op::String(FLAGS_write_coco_json), FLAGS_write_coco_json_variants,
  150. FLAGS_write_coco_json_variant, op::String(FLAGS_write_images), op::String(FLAGS_write_images_format),
  151. op::String(FLAGS_write_video), FLAGS_write_video_fps, FLAGS_write_video_with_audio,
  152. op::String(FLAGS_write_heatmaps), op::String(FLAGS_write_heatmaps_format), op::String(FLAGS_write_video_3d),
  153. op::String(FLAGS_write_video_adam), op::String(FLAGS_write_bvh), op::String(FLAGS_udp_host),
  154. op::String(FLAGS_udp_port)};
  155. opWrapper->configure(wrapperStructOutput);
  156. // No GUI. Equivalent to: opWrapper.configure(WrapperStructGui{});
  157. // Set to single-thread (for sequential processing and/or debugging and/or reducing latency)
  158. if (FLAGS_disable_multi_thread)
  159. opWrapper->disableMultiThreading();
  160. }
  161. catch (const std::exception& e)
  162. {
  163. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  164. }
  165. }
  166. void start()
  167. {
  168. try
  169. {
  170. opWrapper->start();
  171. }
  172. catch (const std::exception& e)
  173. {
  174. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  175. }
  176. }
  177. void stop()
  178. {
  179. try
  180. {
  181. opWrapper->stop();
  182. }
  183. catch (const std::exception& e)
  184. {
  185. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  186. }
  187. }
  188. void exec()
  189. {
  190. try
  191. {
  192. const auto cameraSize = flagsToPoint(op::String(FLAGS_camera_resolution), "-1x-1");
  193. ProducerType producerType;
  194. op::String producerString;
  195. std::tie(producerType, producerString) = flagsToProducer(
  196. op::String(FLAGS_image_dir), op::String(FLAGS_video), op::String(FLAGS_ip_camera), FLAGS_camera,
  197. FLAGS_flir_camera, FLAGS_flir_camera_index);
  198. // Producer (use default to disable any input)
  199. const WrapperStructInput wrapperStructInput{
  200. producerType, producerString, FLAGS_frame_first, FLAGS_frame_step, FLAGS_frame_last,
  201. FLAGS_process_real_time, FLAGS_frame_flip, FLAGS_frame_rotate, FLAGS_frames_repeat,
  202. cameraSize, op::String(FLAGS_camera_parameter_path), FLAGS_frame_undistort, FLAGS_3d_views};
  203. opWrapper->configure(wrapperStructInput);
  204. // GUI (comment or use default argument to disable any visual output)
  205. const WrapperStructGui wrapperStructGui{
  206. flagsToDisplayMode(FLAGS_display, FLAGS_3d), !FLAGS_no_gui_verbose, FLAGS_fullscreen};
  207. opWrapper->configure(wrapperStructGui);
  208. opWrapper->exec();
  209. }
  210. catch (const std::exception& e)
  211. {
  212. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  213. }
  214. }
  215. void emplaceAndPop(std::vector<std::shared_ptr<Datum>>& l)
  216. {
  217. try
  218. {
  219. auto datumsPtr = std::make_shared<std::vector<std::shared_ptr<Datum>>>(l);
  220. opWrapper->emplaceAndPop(datumsPtr);
  221. }
  222. catch (const std::exception& e)
  223. {
  224. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  225. }
  226. }
  227. void waitAndEmplace(std::vector<std::shared_ptr<Datum>>& l)
  228. {
  229. try
  230. {
  231. auto datumsPtr = std::make_shared<std::vector<std::shared_ptr<Datum>>>(l);
  232. opWrapper->waitAndEmplace(datumsPtr);
  233. }
  234. catch (const std::exception& e)
  235. {
  236. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  237. }
  238. }
  239. bool waitAndPop(std::vector<std::shared_ptr<Datum>>& l)
  240. {
  241. try
  242. {
  243. auto datumsPtr = std::make_shared<std::vector<std::shared_ptr<Datum>>>(l);
  244. return opWrapper->waitAndPop(datumsPtr);
  245. }
  246. catch (const std::exception& e)
  247. {
  248. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  249. return false;
  250. }
  251. }
  252. };
  253. std::vector<std::string> getImagesFromDirectory(const std::string& directoryPath)
  254. {
  255. try
  256. {
  257. return getFilesOnDirectory(directoryPath, Extensions::Images);
  258. }
  259. catch (const std::exception& e)
  260. {
  261. error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  262. return {};
  263. }
  264. }
  265. PYBIND11_MODULE(pyopenpose, m) {
  266. // Functions for Init Params
  267. m.def("init_int", &init_int, "Init Function");
  268. m.def("init_argv", &init_argv, "Init Function");
  269. m.def("get_gpu_number", &getGpuNumber, "Get Total GPU");
  270. m.def("get_images_on_directory", &getImagesFromDirectory, "Get Images On Directory");
  271. // Pose Mapping
  272. // Code example in doc/output.md, section Keypoint Ordering in C++/Python
  273. m.def("getPoseBodyPartMapping", &getPoseBodyPartMapping, "getPoseBodyPartMapping");
  274. m.def("getPoseNumberBodyParts", &getPoseNumberBodyParts, "getPoseNumberBodyParts");
  275. m.def("getPosePartPairs", &getPosePartPairs, "getPosePartPairs");
  276. m.def("getPoseMapIndex", &getPoseMapIndex, "getPoseMapIndex");
  277. py::enum_<PoseModel>(m, "PoseModel", py::arithmetic())
  278. .value("BODY_25", PoseModel::BODY_25)
  279. .value("COCO_18", PoseModel::COCO_18)
  280. .value("MPI_15", PoseModel::MPI_15)
  281. .value("MPI_15_4", PoseModel::MPI_15_4)
  282. .value("BODY_25B", PoseModel::BODY_25B)
  283. .value("BODY_135", PoseModel::BODY_135)
  284. .export_values();
  285. // OpenposePython
  286. py::class_<WrapperPython>(m, "WrapperPython")
  287. .def(py::init<>())
  288. .def(py::init<int>())
  289. .def("configure", &WrapperPython::configure)
  290. .def("start", &WrapperPython::start)
  291. .def("stop", &WrapperPython::stop)
  292. .def("execute", &WrapperPython::exec)
  293. .def("emplaceAndPop", &WrapperPython::emplaceAndPop)
  294. .def("waitAndEmplace", &WrapperPython::waitAndEmplace)
  295. .def("waitAndPop", &WrapperPython::waitAndPop)
  296. ;
  297. // Datum Object
  298. py::class_<Datum, std::shared_ptr<Datum>>(m, "Datum")
  299. .def(py::init<>())
  300. .def_readwrite("id", &Datum::id)
  301. .def_readwrite("subId", &Datum::subId)
  302. .def_readwrite("subIdMax", &Datum::subIdMax)
  303. .def_readwrite("name", &Datum::name)
  304. .def_readwrite("frameNumber", &Datum::frameNumber)
  305. .def_readwrite("cvInputData", &Datum::cvInputData)
  306. .def_readwrite("inputNetData", &Datum::inputNetData)
  307. .def_readwrite("outputData", &Datum::outputData)
  308. .def_readwrite("cvOutputData", &Datum::cvOutputData)
  309. .def_readwrite("cvOutputData3D", &Datum::cvOutputData3D)
  310. .def_readwrite("poseKeypoints", &Datum::poseKeypoints)
  311. .def_readwrite("poseIds", &Datum::poseIds)
  312. .def_readwrite("poseScores", &Datum::poseScores)
  313. .def_readwrite("poseHeatMaps", &Datum::poseHeatMaps)
  314. .def_readwrite("poseCandidates", &Datum::poseCandidates)
  315. .def_readwrite("faceRectangles", &Datum::faceRectangles)
  316. .def_readwrite("faceKeypoints", &Datum::faceKeypoints)
  317. .def_readwrite("faceHeatMaps", &Datum::faceHeatMaps)
  318. .def_readwrite("handRectangles", &Datum::handRectangles)
  319. .def_readwrite("handKeypoints", &Datum::handKeypoints)
  320. .def_readwrite("handHeatMaps", &Datum::handHeatMaps)
  321. .def_readwrite("poseKeypoints3D", &Datum::poseKeypoints3D)
  322. .def_readwrite("faceKeypoints3D", &Datum::faceKeypoints3D)
  323. .def_readwrite("handKeypoints3D", &Datum::handKeypoints3D)
  324. .def_readwrite("cameraMatrix", &Datum::cameraMatrix)
  325. .def_readwrite("cameraExtrinsics", &Datum::cameraExtrinsics)
  326. .def_readwrite("cameraIntrinsics", &Datum::cameraIntrinsics)
  327. .def_readwrite("poseNetOutput", &Datum::poseNetOutput)
  328. .def_readwrite("scaleInputToNetInputs", &Datum::scaleInputToNetInputs)
  329. .def_readwrite("netInputSizes", &Datum::netInputSizes)
  330. .def_readwrite("scaleInputToOutput", &Datum::scaleInputToOutput)
  331. .def_readwrite("netOutputSize", &Datum::netOutputSize)
  332. .def_readwrite("scaleNetToOutput", &Datum::scaleNetToOutput)
  333. .def_readwrite("elementRendered", &Datum::elementRendered)
  334. ;
  335. // Rectangle
  336. py::class_<Rectangle<float>>(m, "Rectangle")
  337. .def("__repr__", [](Rectangle<float> &a) { return a.toString(); })
  338. .def(py::init<>())
  339. .def(py::init<float, float, float, float>())
  340. .def_readwrite("x", &Rectangle<float>::x)
  341. .def_readwrite("y", &Rectangle<float>::y)
  342. .def_readwrite("width", &Rectangle<float>::width)
  343. .def_readwrite("height", &Rectangle<float>::height)
  344. ;
  345. // Point
  346. py::class_<Point<int>>(m, "Point")
  347. .def("__repr__", [](Point<int> &a) { return a.toString(); })
  348. .def(py::init<>())
  349. .def(py::init<int, int>())
  350. .def_readwrite("x", &Point<int>::x)
  351. .def_readwrite("y", &Point<int>::y)
  352. ;
  353. #ifdef VERSION_INFO
  354. m.attr("__version__") = VERSION_INFO;
  355. #else
  356. m.attr("__version__") = "dev";
  357. #endif
  358. }
  359. }
  360. // Numpy - op::Array<float> interop
  361. namespace pybind11 { namespace detail {
  362. template <> struct type_caster<op::Array<float>> {
  363. public:
  364. PYBIND11_TYPE_CASTER(op::Array<float>, _("numpy.ndarray"));
  365. // Cast numpy to op::Array<float>
  366. bool load(handle src, bool imp)
  367. {
  368. try
  369. {
  370. UNUSED(imp);
  371. // array b(src, true);
  372. array b = reinterpret_borrow<array>(src);
  373. buffer_info info = b.request();
  374. if (info.format != format_descriptor<float>::format())
  375. op::error("op::Array only supports float32 now", __LINE__, __FUNCTION__, __FILE__);
  376. //std::vector<int> a(info.shape);
  377. std::vector<int> shape(std::begin(info.shape), std::end(info.shape));
  378. // No copy
  379. value = op::Array<float>(shape, (float*)info.ptr);
  380. // Copy
  381. //value = op::Array<float>(shape);
  382. //memcpy(value.getPtr(), info.ptr, value.getVolume()*sizeof(float));
  383. return true;
  384. }
  385. catch (const std::exception& e)
  386. {
  387. op::error(e.what(), __LINE__, __FUNCTION__, __FILE__);
  388. return {};
  389. }
  390. }
  391. // Cast op::Array<float> to numpy
  392. static handle cast(const op::Array<float> &m, return_value_policy, handle defval)
  393. {
  394. UNUSED(defval);
  395. std::string format = format_descriptor<float>::format();
  396. return array(buffer_info(
  397. m.getPseudoConstPtr(),/* Pointer to buffer */
  398. sizeof(float), /* Size of one scalar */
  399. format, /* Python struct-style format descriptor */
  400. m.getSize().size(), /* Number of dimensions */
  401. m.getSize(), /* Buffer dimensions */
  402. m.getStride() /* Strides (in bytes) for each index */
  403. )).release();
  404. }
  405. };
  406. }} // namespace pybind11::detail
  407. // Numpy - op::Matrix interop
  408. namespace pybind11 { namespace detail {
  409. template <> struct type_caster<op::Matrix> {
  410. public:
  411. PYBIND11_TYPE_CASTER(op::Matrix, _("numpy.ndarray"));
  412. // Cast numpy to op::Matrix
  413. bool load(handle src, bool)
  414. {
  415. /* Try a default converting into a Python */
  416. //array b(src, true);
  417. array b = reinterpret_borrow<array>(src);
  418. buffer_info info = b.request();
  419. const int ndims = (int)info.ndim;
  420. decltype(CV_32F) dtype;
  421. size_t elemsize;
  422. if (info.format == format_descriptor<float>::format())
  423. {
  424. if (ndims == 3)
  425. dtype = CV_32FC3;
  426. else
  427. dtype = CV_32FC1;
  428. elemsize = sizeof(float);
  429. }
  430. else if (info.format == format_descriptor<double>::format())
  431. {
  432. if (ndims == 3)
  433. dtype = CV_64FC3;
  434. else
  435. dtype = CV_64FC1;
  436. elemsize = sizeof(double);
  437. }
  438. else if (info.format == format_descriptor<unsigned char>::format())
  439. {
  440. if (ndims == 3)
  441. dtype = CV_8UC3;
  442. else
  443. dtype = CV_8UC1;
  444. elemsize = sizeof(unsigned char);
  445. }
  446. else
  447. {
  448. throw std::logic_error("Unsupported type");
  449. return false;
  450. }
  451. std::vector<int> shape = {(int)info.shape[0], (int)info.shape[1]};
  452. value = op::Matrix(shape[0], shape[1], dtype, info.ptr);
  453. // value = cv::Mat(cv::Size(shape[1], shape[0]), dtype, info.ptr, cv::Mat::AUTO_STEP);
  454. return true;
  455. }
  456. // Cast op::Matrix to numpy
  457. static handle cast(const op::Matrix &matrix, return_value_policy, handle defval)
  458. {
  459. UNUSED(defval);
  460. std::string format = format_descriptor<unsigned char>::format();
  461. size_t elemsize = sizeof(unsigned char);
  462. int dim;
  463. switch(matrix.type()) {
  464. case CV_8U:
  465. format = format_descriptor<unsigned char>::format();
  466. elemsize = sizeof(unsigned char);
  467. dim = 2;
  468. break;
  469. case CV_8UC3:
  470. format = format_descriptor<unsigned char>::format();
  471. elemsize = sizeof(unsigned char);
  472. dim = 3;
  473. break;
  474. case CV_32F:
  475. format = format_descriptor<float>::format();
  476. elemsize = sizeof(float);
  477. dim = 2;
  478. break;
  479. case CV_64F:
  480. format = format_descriptor<double>::format();
  481. elemsize = sizeof(double);
  482. dim = 2;
  483. break;
  484. default:
  485. throw std::logic_error("Unsupported type");
  486. }
  487. std::vector<size_t> bufferdim;
  488. std::vector<size_t> strides;
  489. if (dim == 2) {
  490. bufferdim = {(size_t) matrix.rows(), (size_t) matrix.cols()};
  491. strides = {elemsize * (size_t) matrix.cols(), elemsize};
  492. } else if (dim == 3) {
  493. bufferdim = {(size_t) matrix.rows(), (size_t) matrix.cols(), (size_t) 3};
  494. strides = {(size_t) elemsize * matrix.cols() * 3, (size_t) elemsize * 3, (size_t) elemsize};
  495. }
  496. return array(buffer_info(
  497. matrix.dataPseudoConst(), /* Pointer to buffer */
  498. elemsize, /* Size of one scalar */
  499. format, /* Python struct-style format descriptor */
  500. dim, /* Number of dimensions */
  501. bufferdim, /* Buffer dimensions */
  502. strides /* Strides (in bytes) for each index */
  503. )).release();
  504. }
  505. };
  506. }} // namespace pybind11::detail
  507. #endif
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...