diff --git a/426_YOLOX-Body-Head-Hand/LICENSE b/426_YOLOX-Body-Head-Hand/LICENSE new file mode 100644 index 0000000000..4d5304e0e6 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 Katsuya Hyodo + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/426_YOLOX-Body-Head-Hand/README.md b/426_YOLOX-Body-Head-Hand/README.md new file mode 100644 index 0000000000..9284b25d22 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/README.md @@ -0,0 +1,202 @@ +# Note (Body + Head + Hand) + +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.10229410.svg)](https://doi.org/10.5281/zenodo.10229410) + +Lightweight human detection model generated using a high-quality human dataset. I annotated all the data by myself. Extreme resistance to blur and occlusion. In addition, the recognition rate at short, medium, and long distances has been greatly enhanced. The camera's resistance to darkness and halation has been greatly improved. + +`Head` does not mean `Face`. Thus, the entire head is detected rather than a narrow region of the face. This makes it possible to detect all 360° head orientations. + +## 1. Dataset + - COCO-Hand (14,667 Images, 66,903 labels, All re-annotated manually) + - http://vision.cs.stonybrook.edu/~supreeth/COCO-Hand.zip + - I am adding my own enhancement data to COCO-Hand and re-annotating all images. In other words, only COCO images were cited and no annotation data were cited. + - I have no plans to publish my own dataset. + ``` + body_label_count: 30,729 labels + head_label_count: 26,268 labels + hand_label_count: 18,087 labels + =============================== + Total: 66,903 labels + Total: 14,667 images + ``` + ![image](https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/22b56779-928b-44d8-944c-25431b83e24f) + +## 2. Annotation + + Halfway compromises are never acceptable. + + ![000000000544](https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/557b932b-767b-4f8c-87f5-75f403fa9c50) + + ![000000000716](https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/9acb2308-eba1-4a05-91ed-ccbb6e122f67) + + ![000000002470](https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/c1809eeb-7b2c-41de-a519-9834c804c656) + + ![icon_design drawio (3)](https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/72740ed3-ae9f-4ab7-9b20-bea62c58c7ac) + +## 3. Test + - Python 3.10 + - onnxruntime-gpu v1.16.1 (TensorRT Execution Provider Enabled Binary) + - opencv-contrib-python 4.8.0.76 + - numpy 1.24.3 + - TensorRT 8.5.3-1+cuda11.8 + + ``` + usage: demo_yolox_onnx.py [-h] [-m MODEL] [-v VIDEO] + + options: + -h, --help show this help message and exit + -m MODEL, --model MODEL + -v VIDEO, --video VIDEO + ``` + + - 320x256 CPU Corei9 + + ```bash + python demo/demo_yolox_onnx.py \ + -m yolox_s_body_head_hand_post_0299_0.4983_1x3x256x320.onnx \ + -v 0 + ``` + + https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/5d14b76e-daea-473f-8730-e3b0da0d0164 + + - 160x128 CPU Corei9 + + ```bash + python demo/demo_yolox_onnx.py \ + -m yolox_s_body_head_hand_post_0299_0.4983_1x3x128x160.onnx \ + -v 0 + ``` + + https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/9be1e3e0-afba-45b7-8f4f-24f4fb7e9340 + +- Body-Head-Hand - Nano + ``` + Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.409 + Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.717 + Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.407 + Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.277 + Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.554 + Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.687 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.135 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.380 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.483 + Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.365 + Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.632 + Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.729 + ``` + +- Body-Head-Hand - Tiny + ``` + Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.452 + Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.756 + Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.473 + Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.317 + Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.601 + Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.718 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.143 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.410 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.514 + Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.395 + Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.662 + Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.759 + ``` + +- Body-Head-Hand - S + ``` + Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.498 + Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.790 + Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.522 + Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.343 + Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.672 + Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.806 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.154 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.443 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.557 + Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.425 + Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.726 + Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.836 + ``` + +- Body-Head-Hand - M + ``` + Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.526 + Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.809 + Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.556 + Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.361 + Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.703 + Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.860 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.160 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.464 + Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.576 + Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.437 + Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.751 + Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.885 + ``` + +- Post-Process + + Because I add my own post-processing to the end of the model, which can be inferred by TensorRT, CUDA, and CPU, the benchmarked inference speed is the end-to-end processing speed including all pre-processing and post-processing. EfficientNMS in TensorRT is very slow and should be offloaded to the CPU. + + ![image](https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/db5d5e1f-056c-45ea-9250-07559a7f57f1) + +## 4. Citiation + If this work has contributed in any way to your research or business, I would be happy to be cited in your literature. + ``` + @software{YOLOX-Body-Head-Hand, + author={Katsuya Hyodo}, + title={Lightweight human detection model generated using a high-quality human dataset}, + url={https://github.com/PINTO0309/PINTO_model_zoo/tree/main/426_YOLOX-Body-Head-Hand}, + year={2023}, + month={12}, + doi={10.5281/zenodo.10229410}, + } + ``` + +## 5. Cited + I am very grateful for their excellent work. + - COCO-Hand + + https://vision.cs.stonybrook.edu/~supreeth/ + + ``` + @article{Hand-CNN, + title={Contextual Attention for Hand Detection in the Wild}, + author={Supreeth Narasimhaswamy and Zhengwei Wei and Yang Wang and Justin Zhang and Minh Hoai}, + booktitle={International Conference on Computer Vision (ICCV)}, + year={2019}, + url={https://arxiv.org/pdf/1904.04882.pdf} + } + ``` + - YOLOX + + https://github.com/Megvii-BaseDetection/YOLOX + + ``` + @article{yolox2021, + title={YOLOX: Exceeding YOLO Series in 2021}, + author={Ge, Zheng and Liu, Songtao and Wang, Feng and Li, Zeming and Sun, Jian}, + journal={arXiv preprint arXiv:2107.08430}, + year={2021} + } + ``` + - YOLOX-Colaboratory-Training-Sample + + 高橋かずひと https://github.com/Kazuhito00 + + https://github.com/Kazuhito00/YOLOX-Colaboratory-Training-Sample + + +## 6. TODO +- [ ] Synthesize and retrain the dataset to further improve model performance. [CD-COCO: Complex Distorted COCO database for Scene-Context-Aware computer vision](https://github.com/aymanbegh/cd-coco) + ![image](https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/69603b9b-ab9f-455c-a9c9-c818edc41dba) + ``` + @INPROCEEDINGS{10323035, + author={Beghdadi, Ayman and Beghdadi, Azeddine and Mallem, Malik and Beji, Lotfi and Cheikh, Faouzi Alaya}, + booktitle={2023 11th European Workshop on Visual Information Processing (EUVIP)}, + title={CD-COCO: A Versatile Complex Distorted COCO Database for Scene-Context-Aware Computer Vision}, + year={2023}, + volume={}, + number={}, + pages={1-6}, + doi={10.1109/EUVIP58404.2023.10323035}} + ``` diff --git a/426_YOLOX-Body-Head-Hand/demo/demo_yolox_onnx.py b/426_YOLOX-Body-Head-Hand/demo/demo_yolox_onnx.py new file mode 100644 index 0000000000..635e882b27 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/demo/demo_yolox_onnx.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python + +import copy +import cv2 +import time +import numpy as np +import onnxruntime +from argparse import ArgumentParser +from typing import Tuple, Optional, List + + +class YOLOXONNX(object): + def __init__( + self, + model_path: Optional[str] = 'yolox_s_body_head_hand_post_0299_0.4983_1x3x256x320.onnx', + class_score_th: Optional[float] = 0.35, + providers: Optional[List] = [ + # ( + # 'TensorrtExecutionProvider', { + # 'trt_engine_cache_enable': True, + # 'trt_engine_cache_path': '.', + # 'trt_fp16_enable': True, + # } + # ), + # 'CUDAExecutionProvider', + 'CPUExecutionProvider', + ], + ): + """YOLOXONNX + + Parameters + ---------- + model_path: Optional[str] + ONNX file path for YOLOX + + class_score_th: Optional[float] + Score threshold. Default: 0.35 + + providers: Optional[List] + Name of onnx execution providers + Default: + [ + ( + 'TensorrtExecutionProvider', { + 'trt_engine_cache_enable': True, + 'trt_engine_cache_path': '.', + 'trt_fp16_enable': True, + } + ), + 'CUDAExecutionProvider', + 'CPUExecutionProvider', + ] + """ + # Threshold + self.class_score_th = class_score_th + + # Model loading + session_option = onnxruntime.SessionOptions() + session_option.log_severity_level = 3 + self.onnx_session = onnxruntime.InferenceSession( + model_path, + sess_options=session_option, + providers=providers, + ) + self.providers = self.onnx_session.get_providers() + + self.input_shapes = [ + input.shape for input in self.onnx_session.get_inputs() + ] + self.input_names = [ + input.name for input in self.onnx_session.get_inputs() + ] + self.output_names = [ + output.name for output in self.onnx_session.get_outputs() + ] + + + def __call__( + self, + image: np.ndarray, + ) -> Tuple[np.ndarray, np.ndarray]: + """YOLOXONNX + + Parameters + ---------- + image: np.ndarray + Entire image + + Returns + ------- + boxes: np.ndarray + Predicted boxes: [N, x1, y1, x2, y2] + + scores: np.ndarray + Predicted box scores: [N, score] + """ + temp_image = copy.deepcopy(image) + + # PreProcess + resized_image = self._preprocess( + temp_image, + ) + + # Inference + inferece_image = np.asarray([resized_image], dtype=np.float32) + boxes = self.onnx_session.run( + self.output_names, + {input_name: inferece_image for input_name in self.input_names}, + )[0] + + # PostProcess + result_boxes, result_scores = \ + self._postprocess( + image=temp_image, + boxes=boxes, + ) + + return result_boxes, result_scores + + + def _preprocess( + self, + image: np.ndarray, + swap: Optional[Tuple[int,int,int]] = (2, 0, 1), + ) -> np.ndarray: + """_preprocess + + Parameters + ---------- + image: np.ndarray + Entire image + + swap: tuple + HWC to CHW: (2,0,1) + CHW to HWC: (1,2,0) + HWC to HWC: (0,1,2) + CHW to CHW: (0,1,2) + + Returns + ------- + resized_image: np.ndarray + Resized and normalized image. + """ + # Normalization + BGR->RGB + resized_image = cv2.resize( + image, + ( + int(self.input_shapes[0][3]), + int(self.input_shapes[0][2]), + ) + ) + resized_image = resized_image.transpose(swap) + resized_image = np.ascontiguousarray( + resized_image, + dtype=np.float32, + ) + + return resized_image + + + def _postprocess( + self, + image: np.ndarray, + boxes: np.ndarray, + ): + """_postprocess + + Parameters + ---------- + image: np.ndarray + Entire image. + + boxes: np.ndarray + float32[N, 7] + + Returns + ------- + result_boxes: np.ndarray + Predicted boxes: [N, x1, y1, x2, y2] + + result_scores: np.ndarray + Predicted box confs: [N, score] + """ + image_height = image.shape[0] + image_width = image.shape[1] + + """ + Detector is + N -> Number of boxes detected + batchno -> always 0: BatchNo.0 + + batchno_classid_score_x1y1x2y2: float32[N,7] + """ + image_height = image.shape[0] + image_width = image.shape[1] + + result_boxes = [] + result_scores = [] + + if len(boxes) > 0: + scores = boxes[:, 2:3] + keep_idxs = scores[:, 0] > self.class_score_th + scores_keep = scores[keep_idxs, :] + boxes_keep = boxes[keep_idxs, :] + + if len(boxes_keep) > 0: + for box, score in zip(boxes_keep, scores_keep): + class_id = int(box[1]) + x_min = int(max(0, box[3]) * image_width / self.input_shapes[0][3]) + y_min = int(max(0, box[4]) * image_height / self.input_shapes[0][2]) + x_max = int(min(box[5], self.input_shapes[0][3]) * image_width / self.input_shapes[0][3]) + y_max = int(min(box[6], self.input_shapes[0][2]) * image_height / self.input_shapes[0][2]) + result_boxes.append( + [x_min, y_min, x_max, y_max, class_id] + ) + result_scores.append( + score + ) + + return np.asarray(result_boxes), np.asarray(result_scores) + + +def is_parsable_to_int(s): + try: + int(s) + return True + except ValueError: + return False + + +def main(): + parser = ArgumentParser() + parser.add_argument( + '-m', + '--model', + type=str, + default='yolox_s_body_head_hand_post_0299_0.4983_1x3x256x320.onnx', + ) + parser.add_argument( + '-v', + '--video', + type=str, + default="0", + ) + args = parser.parse_args() + + model = YOLOXONNX( + model_path=args.model, + ) + + cap = cv2.VideoCapture( + int(args.video) if is_parsable_to_int(args.video) else args.video + ) + cap_fps = cap.get(cv2.CAP_PROP_FPS) + w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') + video_writer = cv2.VideoWriter( + filename='output.mp4', + fourcc=fourcc, + fps=cap_fps, + frameSize=(w, h), + ) + + while cap.isOpened(): + res, image = cap.read() + if not res: + break + + debug_image = copy.deepcopy(image) + + start_time = time.perf_counter() + boxes, scores = model(debug_image) + elapsed_time = time.perf_counter() - start_time + cv2.putText( + debug_image, + f'{elapsed_time*1000:.2f} ms', + (10, 30), + cv2.FONT_HERSHEY_SIMPLEX, + 0.7, + (255, 255, 255), + 2, + cv2.LINE_AA, + ) + cv2.putText( + debug_image, + f'{elapsed_time*1000:.2f} ms', + (10, 30), + cv2.FONT_HERSHEY_SIMPLEX, + 0.7, + (0, 0, 255), + 1, + cv2.LINE_AA, + ) + + for box, score in zip(boxes, scores): + classid: int = box[4] + color = (255,255,255) + if classid == 0: + color = (255,0,0) + elif classid == 1: + color = (0,0,255) + elif classid == 2: + color = (0,255,0) + cv2.rectangle( + debug_image, + (box[0], box[1]), + (box[2], box[3]), + (255,255,255), + 2, + ) + cv2.rectangle( + debug_image, + (box[0], box[1]), + (box[2], box[3]), + color, + 1, + ) + cv2.putText( + debug_image, + f'{score[0]:.2f}', + ( + box[0] if box[0]+50 < debug_image.shape[1] else debug_image.shape[1]-50, + box[1]-10 if box[1]-25 > 0 else 20 + ), + cv2.FONT_HERSHEY_SIMPLEX, + 0.7, + (255, 255, 255), + 2, + cv2.LINE_AA, + ) + cv2.putText( + debug_image, + f'{score[0]:.2f}', + ( + box[0] if box[0]+50 < debug_image.shape[1] else debug_image.shape[1]-50, + box[1]-10 if box[1]-25 > 0 else 20 + ), + cv2.FONT_HERSHEY_SIMPLEX, + 0.7, + color, + 1, + cv2.LINE_AA, + ) + + key = cv2.waitKey(1) + if key == 27: # ESC + break + + cv2.imshow("test", debug_image) + video_writer.write(debug_image) + + if video_writer: + video_writer.release() + + if cap: + cap.release() + +if __name__ == "__main__": + main() diff --git a/426_YOLOX-Body-Head-Hand/download_m.sh b/426_YOLOX-Body-Head-Hand/download_m.sh new file mode 100755 index 0000000000..cbcd36b022 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/download_m.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +curl "https://s3.ap-northeast-2.wasabisys.com/pinto-model-zoo/426_YOLOX-Body-Head-Hand/resources_m.tar.gz" -o resources.tar.gz +tar -zxvf resources.tar.gz +rm resources.tar.gz + +echo Download finished. diff --git a/426_YOLOX-Body-Head-Hand/download_n.sh b/426_YOLOX-Body-Head-Hand/download_n.sh new file mode 100755 index 0000000000..93d95bc4b4 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/download_n.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +curl "https://s3.ap-northeast-2.wasabisys.com/pinto-model-zoo/426_YOLOX-Body-Head-Hand/resources_n.tar.gz" -o resources.tar.gz +tar -zxvf resources.tar.gz +rm resources.tar.gz + +echo Download finished. diff --git a/426_YOLOX-Body-Head-Hand/download_s.sh b/426_YOLOX-Body-Head-Hand/download_s.sh new file mode 100755 index 0000000000..da46cb32eb --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/download_s.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +curl "https://s3.ap-northeast-2.wasabisys.com/pinto-model-zoo/426_YOLOX-Body-Head-Hand/resources_s.tar.gz" -o resources.tar.gz +tar -zxvf resources.tar.gz +rm resources.tar.gz + +echo Download finished. diff --git a/426_YOLOX-Body-Head-Hand/download_t.sh b/426_YOLOX-Body-Head-Hand/download_t.sh new file mode 100755 index 0000000000..c04cba3a94 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/download_t.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +curl "https://s3.ap-northeast-2.wasabisys.com/pinto-model-zoo/426_YOLOX-Body-Head-Hand/resources_t.tar.gz" -o resources.tar.gz +tar -zxvf resources.tar.gz +rm resources.tar.gz + +echo Download finished. diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/README.md b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/README.md new file mode 100644 index 0000000000..6cf00fd90a --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/README.md @@ -0,0 +1,209 @@ +# Note +- INPUTS + - `predictions`: `float32 [batches, boxes, 5 + classes]` + + * 5 = [center_x, center_y, width, height, score] +- OUTPUTS + - `batchno_classid_x1y1x2y2_score`: `float32 [final_boxes_count, 7]` + + * NMS boxes + * final_boxes_count (N) ≠ batches + * 7 = [batch_no, classid, x1, y1, x2, y2, score] + +![image](https://github.com/PINTO0309/PINTO_model_zoo/assets/33194443/9d4fecdf-c90e-4e0a-99a5-9c3e61a4cf41) + +# How to generate post-processing ONNX +Simply change the following parameters and run all shells. + +https://github.com/PINTO0309/PINTO_model_zoo/blob/main/420_Gold-YOLO-Hand/post_process_gen_tools/convert_script.sh +```bash +OPSET=11 +BATCHES=1 +BOXES=5040 +CLASSES=1 +``` + +```bash +sudo chmod +x ./convert_script.sh +./convert_script.sh +``` + +# How to change NMS parameters +![image](https://user-images.githubusercontent.com/33194443/178084918-af33bfcc-425f-496e-87fb-1331ef7b2b6e.png) + +https://github.com/PINTO0309/simple-onnx-processing-tools + +Run the script below to directly rewrite the parameters of the ONNX file. +```bash +### Number of output boxes for Gold-YOLO +BOXES=5040 + +### max_output_boxes_per_class +sam4onnx \ +--op_name main01_nonmaxsuppression11 \ +--input_onnx_file_path 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--output_onnx_file_path 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--input_constants main01_max_output_boxes_per_class int64 [10] + +### iou_threshold +sam4onnx \ +--op_name main01_nonmaxsuppression11 \ +--input_onnx_file_path 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--output_onnx_file_path 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--input_constants main01_iou_threshold float32 [0.05] + +### score_threshold +sam4onnx \ +--op_name main01_nonmaxsuppression11 \ +--input_onnx_file_path 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--output_onnx_file_path 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--input_constants main01_score_threshold float32 [0.25] +``` + +# How to merge post-processing into a Gold-YOLO model +Simply execute the following command. + +https://github.com/PINTO0309/simple-onnx-processing-tools + +```bash +################################################### Gold-YOLO + Post-Process +MODEL=gold_yolo +BOXES=5040 +H=256 +W=320 + +snc4onnx \ +--input_onnx_file_paths ${MODEL}_${H}x${W}.onnx 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx + +################################################### 1 Batch + +MODEL=gold_yolo + +BOXES=5040 +H=256 +W=320 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_${H}x${W}.onnx 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx + +BOXES=7560 +H=256 +W=480 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_${H}x${W}.onnx 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx + +BOXES=10080 +H=256 +W=640 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_${H}x${W}.onnx 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx + +BOXES=15120 +H=384 +W=640 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_${H}x${W}.onnx 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx + +BOXES=18900 +H=480 +W=640 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_${H}x${W}.onnx 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx + +BOXES=57960 +H=736 +W=1280 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_${H}x${W}.onnx 30_nms_gold_yolo_m_hand_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx +onnxsim ${MODEL}_post_${H}x${W}.onnx ${MODEL}_post_${H}x${W}.onnx + +################################################### N Batch + +MODEL=gold_yolo + +BOXES=5040 +H=256 +W=320 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_Nx3x${H}x${W}.onnx 31_nms_gold_yolo_m_hand_N_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx + +BOXES=7560 +H=256 +W=480 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_Nx3x${H}x${W}.onnx 31_nms_gold_yolo_m_hand_N_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx + +BOXES=10080 +H=256 +W=640 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_Nx3x${H}x${W}.onnx 31_nms_gold_yolo_m_hand_N_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx + +BOXES=15120 +H=384 +W=640 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_Nx3x${H}x${W}.onnx 31_nms_gold_yolo_m_hand_N_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx + +BOXES=18900 +H=480 +W=640 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_Nx3x${H}x${W}.onnx 31_nms_gold_yolo_m_hand_N_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx + +BOXES=57960 +H=736 +W=1280 +snc4onnx \ +--input_onnx_file_paths ${MODEL}_Nx3x${H}x${W}.onnx 31_nms_gold_yolo_m_hand_N_${BOXES}.onnx \ +--srcop_destop output predictions \ +--output_onnx_file_path ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx +onnxsim ${MODEL}_post_Nx3x${H}x${W}.onnx ${MODEL}_post_Nx3x${H}x${W}.onnx +``` diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/convert_script.sh b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/convert_script.sh new file mode 100755 index 0000000000..98322eec2f --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/convert_script.sh @@ -0,0 +1,345 @@ +#!/bin/bash + +# pip install -U pip \ +# && pip install onnxsim +# && pip install -U simple-onnx-processing-tools \ +# && pip install -U onnx \ +# && python3 -m pip install -U onnx_graphsurgeon --index-url https://pypi.ngc.nvidia.com \ +# && pip install tensorflow==2.12.0 + +MODEL_NAME=yolox_m_body_head_hand +SUFFIX="0299_0.5263_1x3x" + +OPSET=11 +BATCHES=1 +CLASSES=3 + +RESOLUTIONS=( + "128 160 420" + "128 256 672" + "192 320 1260" + "192 416 1638" + "192 640 2520" + "192 800 3150" + "256 320 1680" + "256 416 2184" + "256 448 2352" + "256 640 3360" + "256 800 4200" + "256 960 5040" + "288 1280 7560" + "288 480 2835" + "288 640 3780" + "288 800 4725" + "288 960 5670" + "320 320 2100" + "384 1280 10080" + "384 480 3780" + "384 640 5040" + "384 800 6300" + "384 960 7560" + "416 416 3549" + "480 1280 12600" + "480 640 6300" + "480 800 7875" + "480 960 9450" + "512 512 5376" + "512 640 6720" + "512 896 9408" + "544 1280 14280" + "544 800 8925" + "544 960 10710" + "640 640 8400" + "736 1280 19320" + "576 1024 12096" +) + +for((i=0; i<${#RESOLUTIONS[@]}; i++)) +do + RESOLUTION=(`echo ${RESOLUTIONS[i]}`) + H=${RESOLUTION[0]} + W=${RESOLUTION[1]} + BOXES=${RESOLUTION[2]} + + ################################################### Grids + python make_grids.py -o ${OPSET} -x ${BOXES} -c ${CLASSES} -ih ${H} -iw ${W} + + ################################################### Boxes + Scores + python make_boxes_scores.py -o ${OPSET} -b ${BATCHES} -x ${BOXES} -c ${CLASSES} + python make_cxcywh_y1x1y2x2.py -o ${OPSET} -b ${BATCHES} -x ${BOXES} + + snc4onnx \ + --input_onnx_file_paths 02_boxes_scores_${BOXES}.onnx 03_cxcywh_y1x1y2x2_${BOXES}.onnx \ + --srcop_destop boxes_cxcywh cxcywh \ + --op_prefixes_after_merging 02 03 \ + --output_onnx_file_path 04_boxes_x1y1x2y2_y1x1y2x2_scores_${BOXES}.onnx + + snc4onnx \ + --input_onnx_file_paths 01_grid_${BOXES}.onnx 04_boxes_x1y1x2y2_y1x1y2x2_scores_${BOXES}.onnx \ + --srcop_destop grid_output boxes_scores_input \ + --output_onnx_file_path 04_boxes_x1y1x2y2_y1x1y2x2_scores_${BOXES}.onnx + + + + ################################################### NonMaxSuppression + sog4onnx \ + --op_type Constant \ + --opset ${OPSET} \ + --op_name max_output_boxes_per_class_const \ + --output_variables max_output_boxes_per_class int64 [1] \ + --attributes value int64 [20] \ + --output_onnx_file_path 05_Constant_max_output_boxes_per_class.onnx + + sog4onnx \ + --op_type Constant \ + --opset ${OPSET} \ + --op_name iou_threshold_const \ + --output_variables iou_threshold float32 [1] \ + --attributes value float32 [0.40] \ + --output_onnx_file_path 06_Constant_iou_threshold.onnx + + sog4onnx \ + --op_type Constant \ + --opset ${OPSET} \ + --op_name score_threshold_const \ + --output_variables score_threshold float32 [1] \ + --attributes value float32 [0.25] \ + --output_onnx_file_path 07_Constant_score_threshold.onnx + + + OP=NonMaxSuppression + LOWEROP=${OP,,} + sog4onnx \ + --op_type ${OP} \ + --opset ${OPSET} \ + --op_name ${LOWEROP}${OPSET} \ + --input_variables boxes_var float32 [${BATCHES},${BOXES},4] \ + --input_variables scores_var float32 [${BATCHES},${CLASSES},${BOXES}] \ + --input_variables max_output_boxes_per_class_var int64 [1] \ + --input_variables iou_threshold_var float32 [1] \ + --input_variables score_threshold_var float32 [1] \ + --output_variables selected_indices int64 [\'N\',3] \ + --attributes center_point_box int64 0 \ + --output_onnx_file_path 08_${OP}${OPSET}.onnx + + + snc4onnx \ + --input_onnx_file_paths 05_Constant_max_output_boxes_per_class.onnx 08_${OP}${OPSET}.onnx \ + --srcop_destop max_output_boxes_per_class max_output_boxes_per_class_var \ + --output_onnx_file_path 08_${OP}${OPSET}.onnx + + snc4onnx \ + --input_onnx_file_paths 06_Constant_iou_threshold.onnx 08_${OP}${OPSET}.onnx \ + --srcop_destop iou_threshold iou_threshold_var \ + --output_onnx_file_path 08_${OP}${OPSET}.onnx + + snc4onnx \ + --input_onnx_file_paths 07_Constant_score_threshold.onnx 08_${OP}${OPSET}.onnx \ + --srcop_destop score_threshold score_threshold_var \ + --output_onnx_file_path 08_${OP}${OPSET}.onnx + + soc4onnx \ + --input_onnx_file_path 08_${OP}${OPSET}.onnx \ + --output_onnx_file_path 08_${OP}${OPSET}.onnx \ + --opset ${OPSET} + + + ################################################### Boxes + Scores + NonMaxSuppression + snc4onnx \ + --input_onnx_file_paths 04_boxes_x1y1x2y2_y1x1y2x2_scores_${BOXES}.onnx 08_${OP}${OPSET}.onnx \ + --srcop_destop scores scores_var y1x1y2x2 boxes_var \ + --output_onnx_file_path 09_nms_yolox_${BOXES}.onnx + + + ################################################### Myriad workaround Mul + OP=Mul + LOWEROP=${OP,,} + OPSET=${OPSET} + sog4onnx \ + --op_type ${OP} \ + --opset ${OPSET} \ + --op_name ${LOWEROP}${OPSET} \ + --input_variables workaround_mul_a int64 [\'N\',3] \ + --input_variables workaround_mul_b int64 [1] \ + --output_variables workaround_mul_out int64 [\'N\',3] \ + --output_onnx_file_path 10_${OP}${OPSET}_workaround.onnx + + + ############ Myriad workaround Constant + sog4onnx \ + --op_type Constant \ + --opset ${OPSET} \ + --op_name workaround_mul_const_op \ + --output_variables workaround_mul_const int64 [1] \ + --attributes value int64 [1] \ + --output_onnx_file_path 11_Constant_workaround_mul.onnx + + ############ Myriad workaround Mul + Myriad workaround Constant + snc4onnx \ + --input_onnx_file_paths 11_Constant_workaround_mul.onnx 10_${OP}${OPSET}_workaround.onnx \ + --srcop_destop workaround_mul_const workaround_mul_b \ + --output_onnx_file_path 11_Constant_workaround_mul.onnx + + + + ################################################### NonMaxSuppression + Myriad workaround Mul + snc4onnx \ + --input_onnx_file_paths 09_nms_yolox_${BOXES}.onnx 11_Constant_workaround_mul.onnx \ + --srcop_destop selected_indices workaround_mul_a \ + --output_onnx_file_path 09_nms_yolox_${BOXES}.onnx + + + + ################################################### Score GatherND + python make_score_gather_nd.py -b ${BATCHES} -x ${BOXES} -c ${CLASSES} + + python -m tf2onnx.convert \ + --opset ${OPSET} \ + --tflite saved_model_postprocess/nms_score_gather_nd.tflite \ + --output 12_nms_score_gather_nd.onnx + + sor4onnx \ + --input_onnx_file_path 12_nms_score_gather_nd.onnx \ + --old_new ":0" "" \ + --search_mode "suffix_match" \ + --output_onnx_file_path 12_nms_score_gather_nd.onnx + + sor4onnx \ + --input_onnx_file_path 12_nms_score_gather_nd.onnx \ + --old_new "serving_default_input_1" "gn_scores" \ + --output_onnx_file_path 12_nms_score_gather_nd.onnx \ + --mode inputs + + sor4onnx \ + --input_onnx_file_path 12_nms_score_gather_nd.onnx \ + --old_new "serving_default_input_2" "gn_selected_indices" \ + --output_onnx_file_path 12_nms_score_gather_nd.onnx \ + --mode inputs + + sor4onnx \ + --input_onnx_file_path 12_nms_score_gather_nd.onnx \ + --old_new "PartitionedCall" "final_scores" \ + --output_onnx_file_path 12_nms_score_gather_nd.onnx \ + --mode outputs + + python make_input_output_shape_update.py \ + --input_onnx_file_path 12_nms_score_gather_nd.onnx \ + --output_onnx_file_path 12_nms_score_gather_nd.onnx \ + --input_names gn_scores \ + --input_names gn_selected_indices \ + --input_shapes ${BATCHES} ${CLASSES} ${BOXES} \ + --input_shapes N 3 \ + --output_names final_scores \ + --output_shapes N 1 + + onnxsim 12_nms_score_gather_nd.onnx 12_nms_score_gather_nd.onnx + onnxsim 12_nms_score_gather_nd.onnx 12_nms_score_gather_nd.onnx + + + ################################################### NonMaxSuppression + Score GatherND + snc4onnx \ + --input_onnx_file_paths 09_nms_yolox_${BOXES}.onnx 12_nms_score_gather_nd.onnx \ + --srcop_destop scores gn_scores workaround_mul_out gn_selected_indices \ + --output_onnx_file_path 09_nms_yolox_${BOXES}_nd.onnx + + onnxsim 09_nms_yolox_${BOXES}_nd.onnx 09_nms_yolox_${BOXES}_nd.onnx + onnxsim 09_nms_yolox_${BOXES}_nd.onnx 09_nms_yolox_${BOXES}_nd.onnx + + + ################################################### Final Batch Nums + python make_final_batch_nums_final_class_nums_final_box_nums.py + + + ################################################### Boxes GatherND + python make_box_gather_nd.py + + python -m tf2onnx.convert \ + --opset ${OPSET} \ + --tflite saved_model_postprocess/nms_box_gather_nd.tflite \ + --output 14_nms_box_gather_nd.onnx + + sor4onnx \ + --input_onnx_file_path 14_nms_box_gather_nd.onnx \ + --old_new ":0" "" \ + --search_mode "suffix_match" \ + --output_onnx_file_path 14_nms_box_gather_nd.onnx + + sor4onnx \ + --input_onnx_file_path 14_nms_box_gather_nd.onnx \ + --old_new "serving_default_input_1" "gn_boxes" \ + --output_onnx_file_path 14_nms_box_gather_nd.onnx \ + --mode inputs + + sor4onnx \ + --input_onnx_file_path 14_nms_box_gather_nd.onnx \ + --old_new "serving_default_input_2" "gn_box_selected_indices" \ + --output_onnx_file_path 14_nms_box_gather_nd.onnx \ + --mode inputs + + sor4onnx \ + --input_onnx_file_path 14_nms_box_gather_nd.onnx \ + --old_new "PartitionedCall" "final_boxes" \ + --output_onnx_file_path 14_nms_box_gather_nd.onnx \ + --mode outputs + + python make_input_output_shape_update.py \ + --input_onnx_file_path 14_nms_box_gather_nd.onnx \ + --output_onnx_file_path 14_nms_box_gather_nd.onnx \ + --input_names gn_boxes \ + --input_names gn_box_selected_indices \ + --input_shapes ${BATCHES} ${BOXES} 4 \ + --input_shapes N 2 \ + --output_names final_boxes \ + --output_shapes N 4 + + onnxsim 14_nms_box_gather_nd.onnx 14_nms_box_gather_nd.onnx + onnxsim 14_nms_box_gather_nd.onnx 14_nms_box_gather_nd.onnx + + + ################################################### nms_yolox_xxx_nd + nms_final_batch_nums_final_class_nums_final_box_nums + snc4onnx \ + --input_onnx_file_paths 09_nms_yolox_${BOXES}_nd.onnx 13_nms_final_batch_nums_final_class_nums_final_box_nums.onnx \ + --srcop_destop workaround_mul_out bc_input \ + --op_prefixes_after_merging main01 sub01 \ + --output_onnx_file_path 15_nms_yolox_${BOXES}_split.onnx + + + + ################################################### nms_yolox_${BOXES}_split + nms_box_gather_nd + snc4onnx \ + --input_onnx_file_paths 15_nms_yolox_${BOXES}_split.onnx 14_nms_box_gather_nd.onnx \ + --srcop_destop x1y1x2y2 gn_boxes final_box_nums gn_box_selected_indices \ + --output_onnx_file_path 16_nms_yolox_${BOXES}_merged.onnx + + onnxsim 16_nms_yolox_${BOXES}_merged.onnx 16_nms_yolox_${BOXES}_merged.onnx + onnxsim 16_nms_yolox_${BOXES}_merged.onnx 16_nms_yolox_${BOXES}_merged.onnx + + + + ################################################### nms output merge + python make_nms_outputs_merge.py + + onnxsim 17_nms_batchno_classid_x1y1x2y2_cat.onnx 17_nms_batchno_classid_x1y1x2y2_cat.onnx + + + ################################################### merge + snc4onnx \ + --input_onnx_file_paths 16_nms_yolox_${BOXES}_merged.onnx 17_nms_batchno_classid_x1y1x2y2_cat.onnx \ + --srcop_destop final_batch_nums cat_batch final_class_nums cat_classid final_scores cat_score final_boxes cat_x1y1x2y2 \ + --output_onnx_file_path 18_nms_yolox_${BOXES}.onnx + + onnxsim 18_nms_yolox_${BOXES}.onnx 18_nms_yolox_${BOXES}.onnx + + + ################################################### yolox + Post-Process + snc4onnx \ + --input_onnx_file_paths ${MODEL_NAME}_${SUFFIX}${H}x${W}.onnx 18_nms_yolox_${BOXES}.onnx \ + --srcop_destop output predictions \ + --output_onnx_file_path ${MODEL_NAME}_post_${SUFFIX}${H}x${W}.onnx + onnxsim ${MODEL_NAME}_post_${SUFFIX}${H}x${W}.onnx ${MODEL_NAME}_post_${SUFFIX}${H}x${W}.onnx + onnxsim ${MODEL_NAME}_post_${SUFFIX}${H}x${W}.onnx ${MODEL_NAME}_post_${SUFFIX}${H}x${W}.onnx + + ################################################### cleaning + rm 0*_*.onnx + rm 1*_*.onnx +done diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/export_onnx.sh b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/export_onnx.sh new file mode 100755 index 0000000000..50b4a2fb52 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/export_onnx.sh @@ -0,0 +1,71 @@ +TYPE=m +MODEL_NAME=yolox_m_body_head_hand +SUFFIX="0299_0.5263_1x3x" +MODEL_PATH=yolox_outputs_m/YOLOX_outputs/m/best_ckpt_0299_0.5263.pth + +RESOLUTIONS=( + "128 160 420" + "128 256 672" + "192 320 1260" + "192 416 1638" + "192 640 2520" + "192 800 3150" + "256 320 1680" + "256 416 2184" + "256 448 2352" + "256 640 3360" + "256 800 4200" + "256 960 5040" + "288 1280 7560" + "288 480 2835" + "288 640 3780" + "288 800 4725" + "288 960 5670" + "320 320 2100" + "384 1280 10080" + "384 480 3780" + "384 640 5040" + "384 800 6300" + "384 960 7560" + "416 416 3549" + "480 1280 12600" + "480 640 6300" + "480 800 7875" + "480 960 9450" + "512 512 5376" + "512 640 6720" + "512 896 9408" + "544 1280 14280" + "544 800 8925" + "544 960 10710" + "640 640 8400" + "736 1280 19320" + "576 1024 12096" +) + +for((i=0; i<${#RESOLUTIONS[@]}; i++)) +do + RESOLUTION=(`echo ${RESOLUTIONS[i]}`) + H=${RESOLUTION[0]} + W=${RESOLUTION[1]} + + python export_onnx.py \ + --output-name ${MODEL_NAME}_${SUFFIX}${H}x${W}.onnx \ + -n yolox-${TYPE} \ + -f ${TYPE}.py \ + -c ${MODEL_PATH} \ + -s "(${H}, ${W})" + + sng4onnx \ + --input_onnx_file_path ${MODEL_NAME}_${SUFFIX}${H}x${W}.onnx \ + --output_onnx_file_path ${MODEL_NAME}_${SUFFIX}${H}x${W}.onnx +done + +python export_onnx.py \ +--output-name ${MODEL_NAME}_1x3xHxW.onnx \ +-n yolox-${TYPE} \ +-f ${TYPE}.py \ +-c ${MODEL_PATH} \ +--dynamic + +rm ${MODEL_NAME}_1x3xHxW.onnx \ No newline at end of file diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_box_gather_nd.py b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_box_gather_nd.py new file mode 100644 index 0000000000..c3292a3e6b --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_box_gather_nd.py @@ -0,0 +1,63 @@ +import os +os.environ['CUDA_VISIBLE_DEVICES'] = '-1' +import tensorflow as tf +import numpy as np +np.random.seed(0) +from argparse import ArgumentParser + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument( + '-b', + '--batches', + type=int, + default=1, + help='batch size' + ) + parser.add_argument( + '-x', + '--boxes', + type=int, + default=5040, + help='boxes' + ) + args = parser.parse_args() + BATCHES = args.batches + BOXES = args.boxes + + # Create a model + boxes = tf.keras.layers.Input( + shape=[ + BOXES, + 4, + ], + batch_size=BATCHES, + dtype=tf.float32, + ) + + selected_indices = tf.keras.layers.Input( + shape=[ + 2, + ], + dtype=tf.int64, + ) + + gathered_boxes = tf.gather_nd( + boxes, + selected_indices, + batch_dims=0, + ) + gathered_boxes_casted = tf.cast(gathered_boxes, dtype=tf.float32) + + model = tf.keras.models.Model(inputs=[boxes, selected_indices], outputs=[gathered_boxes_casted]) + model.summary() + output_path = 'saved_model_postprocess' + tf.saved_model.save(model, output_path) + converter = tf.lite.TFLiteConverter.from_keras_model(model) + converter.target_spec.supported_ops = [ + tf.lite.OpsSet.TFLITE_BUILTINS, + tf.lite.OpsSet.SELECT_TF_OPS + ] + tflite_model = converter.convert() + open(f"{output_path}/nms_box_gather_nd.tflite", "wb").write(tflite_model) \ No newline at end of file diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_boxes_scores.py b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_boxes_scores.py new file mode 100644 index 0000000000..07e83a4cc3 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_boxes_scores.py @@ -0,0 +1,96 @@ +#! /usr/bin/env python + +import torch +import torch.nn as nn +import onnx +from onnxsim import simplify +from argparse import ArgumentParser + +""" +prediction [1, 5040, 85] + +80 classes + +85 + +[0] -> center_x +[1] -> center_y +[2] -> width +[3] -> height +[4] -> box_score +[5]-[84] -> class_score +""" + + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, x): + boxes = x[..., :4] # xywh [n, boxes, 4] + box_scores = x[..., 4:5] # [n, boxes, 1] + class_scores = x[..., 5:] # [n, boxes, 80] + scores = torch.sqrt(box_scores * class_scores) + scores = scores.permute(0,2,1) + return boxes, scores + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument( + '-o', + '--opset', + type=int, + default=11, + help='onnx opset' + ) + parser.add_argument( + '-b', + '--batches', + type=int, + default=1, + help='batch size' + ) + parser.add_argument( + '-x', + '--boxes', + type=int, + default=5040, + help='boxes' + ) + parser.add_argument( + '-c', + '--classes', + type=int, + default=80, + help='classes' + ) + args = parser.parse_args() + + model = Model() + + MODEL = f'02_boxes_scores' + OPSET=args.opset + BATCHES = args.batches + BOXES = args.boxes + CLASSES = args.classes + + onnx_file = f"{MODEL}_{BOXES}.onnx" + x = torch.randn(BATCHES, BOXES, CLASSES+5) + + torch.onnx.export( + model, + args=(x), + f=onnx_file, + opset_version=OPSET, + input_names = ['boxes_scores_input'], + output_names=['boxes_cxcywh','scores'], + ) + model_onnx1 = onnx.load(onnx_file) + model_onnx1 = onnx.shape_inference.infer_shapes(model_onnx1) + onnx.save(model_onnx1, onnx_file) + + model_onnx2 = onnx.load(onnx_file) + model_simp, check = simplify(model_onnx2) + onnx.save(model_simp, onnx_file) + diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_cxcywh_y1x1y2x2.py b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_cxcywh_y1x1y2x2.py new file mode 100644 index 0000000000..38c2c03046 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_cxcywh_y1x1y2x2.py @@ -0,0 +1,73 @@ +#! /usr/bin/env python + +import torch +import torch.nn as nn +import numpy as np +import onnx +from onnxsim import simplify +from argparse import ArgumentParser + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, cxcywh): + x1 = (cxcywh[..., 0:1] - cxcywh[..., 2:3] / 2) # top left x + y1 = (cxcywh[..., 1:2] - cxcywh[..., 3:4] / 2) # top left y + x2 = (cxcywh[..., 0:1] + cxcywh[..., 2:3] / 2) # bottom right x + y2 = (cxcywh[..., 1:2] + cxcywh[..., 3:4] / 2) # bottom right y + x1y1x2y2 = torch.cat([x1,y1,x2,y2], dim=2) + y1x1y2x2 = torch.cat([y1,x1,y2,x2], dim=2) + return x1y1x2y2, y1x1y2x2 + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument( + '-o', + '--opset', + type=int, + default=11, + help='onnx opset' + ) + parser.add_argument( + '-b', + '--batches', + type=int, + default=1, + help='batch size' + ) + parser.add_argument( + '-x', + '--boxes', + type=int, + default=5040, + help='boxes' + ) + args = parser.parse_args() + + model = Model() + + MODEL = f'03_cxcywh_y1x1y2x2' + OPSET=args.opset + BATCHES = args.batches + BOXES = args.boxes + + onnx_file = f"{MODEL}_{BOXES}.onnx" + cxcywh = torch.randn(BATCHES, BOXES, 4) + + torch.onnx.export( + model, + args=(cxcywh), + f=onnx_file, + opset_version=OPSET, + input_names = ['cxcywh'], + output_names=['x1y1x2y2', 'y1x1y2x2'], + ) + model_onnx1 = onnx.load(onnx_file) + model_onnx1 = onnx.shape_inference.infer_shapes(model_onnx1) + onnx.save(model_onnx1, onnx_file) + + model_onnx2 = onnx.load(onnx_file) + model_simp, check = simplify(model_onnx2) + onnx.save(model_simp, onnx_file) diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_final_batch_nums_final_class_nums_final_box_nums.py b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_final_batch_nums_final_class_nums_final_box_nums.py new file mode 100644 index 0000000000..09dfc39a66 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_final_batch_nums_final_class_nums_final_box_nums.py @@ -0,0 +1,61 @@ +#! /usr/bin/env python + +import torch +import torch.nn as nn +import onnx +import numpy as np +from onnxsim import simplify +from argparse import ArgumentParser + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, x): + batch_nums = x[:, 0:1].to(torch.float32) # batch number + class_nums = x[:, 1:2].to(torch.float32) # class ids + box_nums = x[:, [0,2]] # batch number + box number + return batch_nums, class_nums, box_nums + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument( + '-o', + '--opset', + type=int, + default=11, + help='onnx opset' + ) + args = parser.parse_args() + + model = Model() + + MODEL = f'13_nms_final_batch_nums_final_class_nums_final_box_nums' + OPSET=args.opset + + onnx_file = f"{MODEL}.onnx" + x = torch.ones([1, 3], dtype=torch.int64) + + torch.onnx.export( + model, + args=(x), + f=onnx_file, + opset_version=OPSET, + input_names=['bc_input'], + output_names=['final_batch_nums','final_class_nums','final_box_nums'], + dynamic_axes={ + 'bc_input': {0: 'N'}, + 'final_batch_nums': {0: 'N'}, + 'final_class_nums': {0: 'N'}, + 'final_box_nums': {0: 'N'}, + } + ) + model_onnx1 = onnx.load(onnx_file) + model_onnx1 = onnx.shape_inference.infer_shapes(model_onnx1) + onnx.save(model_onnx1, onnx_file) + + model_onnx2 = onnx.load(onnx_file) + model_simp, check = simplify(model_onnx2) + onnx.save(model_simp, onnx_file) + diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_grids.py b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_grids.py new file mode 100644 index 0000000000..39d68d8b6e --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_grids.py @@ -0,0 +1,117 @@ +#! /usr/bin/env python + +import torch +import torch.nn as nn +import onnx +import numpy as np +from onnxsim import simplify +from typing import List +from argparse import ArgumentParser + +class Model(nn.Module): + def __init__(self, img_size, strides): + super(Model, self).__init__() + + self.img_size = img_size + self.strides = strides + + def forward(self, x): + hsizes = [self.img_size[0] // stride for stride in self.strides] + wsizes = [self.img_size[1] // stride for stride in self.strides] + + grids = [] + expanded_strides = [] + + for hsize, wsize, stride in zip(hsizes, wsizes, self.strides): + ix = torch.arange(wsize) + iy = torch.arange(hsize) + yv, xv = torch.meshgrid([iy, ix], indexing='ij') + grid = torch.stack((xv, yv), 2).reshape(1, -1, 2) + grids.append(grid) + shape = grid.shape[:2] + expanded_strides.append(torch.full((*shape, 1), stride)) + + grids = torch.cat(grids, 1) + expanded_strides = torch.cat(expanded_strides, 1) + x[..., :2] = (x[..., :2] + grids) * expanded_strides + x[..., 2:4] = torch.exp(x[..., 2:4]) * expanded_strides + return x + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument( + '-o', + '--opset', + type=int, + default=11, + help='onnx opset' + ) + parser.add_argument( + '-ih', + '--image_height', + type=int, + default=416, + help='height' + ) + parser.add_argument( + '-iw', + '--image_width', + type=int, + default=416, + help='width' + ) + parser.add_argument( + '-s', + '--strides', + type=int, + nargs='*', + default=[8, 16, 32], + help='strides' + ) + parser.add_argument( + '-x', + '--boxes', + type=int, + default=3549, + help='boxes' + ) + parser.add_argument( + '-c', + '--classes', + type=int, + default=16, + help='classes' + ) + args = parser.parse_args() + + image_height: int = args.image_height + image_width: int = args.image_width + strides: List[int] = args.strides + boxes: int = args.boxes + classes: int = args.classes + model = Model(img_size=[image_height, image_width], strides=strides) + + MODEL = f'01_grid' + OPSET=args.opset + + onnx_file = f"{MODEL}_{boxes}.onnx" + x = torch.randn(1, boxes, classes+5) + + torch.onnx.export( + model, + args=(x), + f=onnx_file, + opset_version=OPSET, + input_names = ['predictions'], + output_names=['grid_output'], + ) + model_onnx1 = onnx.load(onnx_file) + model_onnx1 = onnx.shape_inference.infer_shapes(model_onnx1) + onnx.save(model_onnx1, onnx_file) + + model_onnx2 = onnx.load(onnx_file) + model_simp, check = simplify(model_onnx2) + onnx.save(model_simp, onnx_file) + + diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_input_output_shape_update.py b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_input_output_shape_update.py new file mode 100644 index 0000000000..f00d8fc5dc --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_input_output_shape_update.py @@ -0,0 +1,76 @@ +import onnx +from onnx.tools import update_model_dims +from argparse import ArgumentParser + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument( + '-if', + '--input_onnx_file_path', + type=str, + required=True, + help='INPUT ONNX file path' + ) + parser.add_argument( + '-of', + '--output_onnx_file_path', + type=str, + required=True, + help='OUTPUT ONNX file path' + ) + parser.add_argument( + '-i', + '--input_names', + type=str, + action='append', + help='input names' + ) + parser.add_argument( + '-is', + '--input_shapes', + type=str, + nargs='+', + action='append', + help='input shapes' + ) + parser.add_argument( + '-o', + '--output_names', + type=str, + action='append', + help='output names' + ) + parser.add_argument( + '-os', + '--output_shapes', + type=str, + nargs='+', + action='append', + help='output shapes' + ) + + args = parser.parse_args() + INPUT_MODEL_PATH = args.input_onnx_file_path + OUTPUT_MODEL_PATH = args.output_onnx_file_path + INPUT_NAMES = args.input_names + INPUT_SHAPES = args.input_shapes + OUTPUT_NAMES = args.output_names + OUTPUT_SHAPES = args.output_shapes + + input_names = [name for name in INPUT_NAMES] + input_shapes = [shape for shape in INPUT_SHAPES] + output_names = [name for name in OUTPUT_NAMES] + output_shapes = [shape for shape in OUTPUT_SHAPES] + + input_dicts = {name:shape for (name, shape) in zip(input_names, input_shapes)} + output_dicts = {name:shape for (name, shape) in zip(output_names, output_shapes)} + + model = onnx.load(INPUT_MODEL_PATH) + updated_model = update_model_dims.update_inputs_outputs_dims( + model=model, + input_dims=input_dicts, + output_dims=output_dicts, + ) + + onnx.save(updated_model, OUTPUT_MODEL_PATH) \ No newline at end of file diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_nms_outputs_merge.py b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_nms_outputs_merge.py new file mode 100644 index 0000000000..76d090dd92 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_nms_outputs_merge.py @@ -0,0 +1,64 @@ +#! /usr/bin/env python + +import torch +import torch.nn as nn +import onnx +from onnxsim import simplify +from argparse import ArgumentParser + + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, batch, classid, score, x1y1x2y2): + batchno_classid_score_x1y1x2y2_cat = torch.cat([batch, classid, score, x1y1x2y2], dim=1) + return batchno_classid_score_x1y1x2y2_cat + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument( + '-o', + '--opset', + type=int, + default=11, + help='onnx opset' + ) + args = parser.parse_args() + + model = Model() + + MODEL = f'17_nms_batchno_classid_x1y1x2y2_cat' + + onnx_file = f"{MODEL}.onnx" + OPSET=args.opset + + x1 = torch.ones([1, 1], dtype=torch.float32) + x2 = torch.ones([1, 1], dtype=torch.float32) + x3 = torch.ones([1, 1], dtype=torch.float32) + x4 = torch.ones([1, 4], dtype=torch.float32) + + torch.onnx.export( + model, + args=(x1,x2,x3,x4), + f=onnx_file, + opset_version=OPSET, + input_names=['cat_batch','cat_classid','cat_score','cat_x1y1x2y2'], + output_names=['batchno_classid_score_x1y1x2y2'], + dynamic_axes={ + 'cat_batch': {0: 'N'}, + 'cat_classid': {0: 'N'}, + 'cat_score': {0: 'N'}, + 'cat_x1y1x2y2': {0: 'N'}, + 'batchno_classid_score_x1y1x2y2': {0: 'N'}, + } + ) + model_onnx1 = onnx.load(onnx_file) + model_onnx1 = onnx.shape_inference.infer_shapes(model_onnx1) + onnx.save(model_onnx1, onnx_file) + + model_onnx2 = onnx.load(onnx_file) + model_simp, check = simplify(model_onnx2) + onnx.save(model_simp, onnx_file) + diff --git a/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_score_gather_nd.py b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_score_gather_nd.py new file mode 100644 index 0000000000..c9cbc0f8a5 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/post_process_gen_tools/make_score_gather_nd.py @@ -0,0 +1,72 @@ +import os +os.environ['CUDA_VISIBLE_DEVICES'] = '-1' +import tensorflow as tf +import numpy as np +np.random.seed(0) +from argparse import ArgumentParser + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument( + '-b', + '--batches', + type=int, + default=1, + help='batch size' + ) + parser.add_argument( + '-x', + '--boxes', + type=int, + default=5040, + help='boxes' + ) + parser.add_argument( + '-c', + '--classes', + type=int, + default=80, + help='classes' + ) + args = parser.parse_args() + BATCHES = args.batches + BOXES = args.boxes + CLASSES = args.classes + + + # Create a model + scores = tf.keras.layers.Input( + shape=[ + CLASSES, + BOXES, + ], + batch_size=BATCHES, + dtype=tf.float32, + ) + + selected_indices = tf.keras.layers.Input( + shape=[ + 3, + ], + dtype=tf.int64, + ) + + gathered_scores = tf.gather_nd( + scores, + selected_indices, + batch_dims=0, + ) + expands_scores = gathered_scores[:,np.newaxis] + + model = tf.keras.models.Model(inputs=[scores,selected_indices], outputs=[expands_scores]) + model.summary() + output_path = 'saved_model_postprocess' + tf.saved_model.save(model, output_path) + converter = tf.lite.TFLiteConverter.from_keras_model(model) + converter.target_spec.supported_ops = [ + tf.lite.OpsSet.TFLITE_BUILTINS, + tf.lite.OpsSet.SELECT_TF_OPS + ] + tflite_model = converter.convert() + open(f"{output_path}/nms_score_gather_nd.tflite", "wb").write(tflite_model) \ No newline at end of file diff --git a/426_YOLOX-Body-Head-Hand/url.txt b/426_YOLOX-Body-Head-Hand/url.txt new file mode 100644 index 0000000000..203a15bd17 --- /dev/null +++ b/426_YOLOX-Body-Head-Hand/url.txt @@ -0,0 +1,6 @@ +https://github.com/Megvii-BaseDetection/YOLOX +https://github.com/Kazuhito00/YOLOX-Colaboratory-Training-Sample + +https://github.com/PINTO0309/onnx2tf +https://github.com/PINTO0309/simple-onnx-processing-tools + diff --git a/README.md b/README.md index 3da0bc22a1..76e5953ea8 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,7 @@ I have been working on quantization of various models as a hobby, but I have ski |422|Gold-YOLO-Head-Hand|[■■■](https://github.com/PINTO0309/PINTO_model_zoo/tree/main/422_Gold-YOLO-Head-Hand)|||||||||||⚫|Head,Hand| |424|Gold-YOLO-Body|[■■■](https://github.com/PINTO0309/PINTO_model_zoo/tree/main/424_Gold-YOLO-Body)|||||||||||⚫|Body| |425|Gold-YOLO-Body-Head-Hand|[■■■](https://github.com/PINTO0309/PINTO_model_zoo/tree/main/425_Gold-YOLO-Body-Head-Hand)|||||||||||⚫|Body,Head,Hand| +|426|YOLOX-Body-Head-Hand|[■■■](https://github.com/PINTO0309/PINTO_model_zoo/tree/main/426_YOLOX-Body-Head-Hand)|||||||||||⚫|Body,Head,Hand| ### 3. 3D Object Detection |No.|Model Name|Link|FP32|FP16|INT8|TPU|DQ|WQ|OV|CM|TFJS|TF-TRT|ONNX|Remarks| |:-|:-|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-:|:-|