Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nanodet C API. Onnx and Libtorch (JIT) modules implementations and Libtorch Installation. #352

Merged
merged 111 commits into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
111 commits
Select commit Hold shift + click to select a range
02a2513
Onnx and Jit tracing-scripting implementation with python and c api i…
Nov 22, 2022
a402954
Implementation of libtorch and torch vision installation as part of t…
Nov 22, 2022
cbf2a9a
add licence and file name corection
Nov 22, 2022
cce417f
style, inconclusive cppcheck fixes.
Nov 23, 2022
c433aeb
Merge branch 'develop' into nanodet_c
ad-daniel Nov 23, 2022
a1a4ac2
Fixes for C API initilization errors
Nov 24, 2022
b15de60
Deleting no used code
Nov 24, 2022
42815d3
macos cppcheck -> C style fixes
Nov 24, 2022
08ed2c1
macos cppcheck -c style fixes
Nov 24, 2022
75deceb
c-style pointer delceration fixes
Nov 24, 2022
0d4b1be
c-style pointer delceration fixes
Nov 24, 2022
477f842
cpp casting casting fixes
Nov 24, 2022
f1fed96
bug fixes
Nov 24, 2022
9aad554
Merge branch 'develop' into nanodet_c
ad-daniel Nov 24, 2022
e26e265
Update projects/python/perception/object_detection_2d/nanodet/export_…
ManosMpampis Nov 25, 2022
8fbf436
Update install_torch_c_api.sh
ManosMpampis Nov 25, 2022
882d0a1
Update dependencies/install_torch_c_api.sh
ManosMpampis Nov 25, 2022
e3e1eea
Update include/nanodet_c.h
ManosMpampis Nov 25, 2022
83bdfbd
Update include/nanodet_c.h
ManosMpampis Nov 25, 2022
c7376e2
Update include/nanodet_c.h
ManosMpampis Nov 25, 2022
fb4e6b6
Update include/nanodet_c.h
ManosMpampis Nov 25, 2022
8f7fb24
Update include/opendr_utils.h
ManosMpampis Nov 25, 2022
61412b3
Update include/target.h
ManosMpampis Nov 25, 2022
16e61c2
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
f9a0bf4
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
2bca053
Update nanodet.md
ManosMpampis Nov 25, 2022
8549689
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
730d192
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
ef23d94
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
c41d578
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
96e4c0e
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
bda772f
Update nanodet.md
ManosMpampis Nov 25, 2022
0feb2f2
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
96978ce
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
e242b78
Update Makefile
ManosMpampis Nov 25, 2022
51f4684
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
a9537ec
Update docs/reference/nanodet.md
ManosMpampis Nov 25, 2022
5589966
Update nanodet.md
ManosMpampis Nov 25, 2022
e3f6616
Update projects/c_api/Makefile
ManosMpampis Nov 25, 2022
aca73a2
Update projects/python/perception/object_detection_2d/nanodet/README.md
ManosMpampis Nov 25, 2022
bf61b2c
Update eval_demo.py
ManosMpampis Nov 25, 2022
5f0c364
Update projects/python/perception/object_detection_2d/nanodet/export_…
ManosMpampis Nov 25, 2022
9128f7d
Update projects/python/perception/object_detection_2d/nanodet/README.md
ManosMpampis Nov 25, 2022
3631fc4
Update projects/python/perception/object_detection_2d/nanodet/README.md
ManosMpampis Nov 25, 2022
f06f58a
Merge branch 'develop' into nanodet_c
ad-daniel Nov 25, 2022
5c1e458
installing libtorch and vision with respect to CUDA of the user
Nov 28, 2022
c547fc2
better explanations of variables in optimization runtimes
Nov 28, 2022
3d3a3a6
small typing fixes
Nov 28, 2022
5fb0755
Merge branch 'develop' into nanodet_c
ManosMpampis Nov 30, 2022
b8c543c
Merge branch 'develop' into nanodet_c
ad-daniel Dec 6, 2022
4006735
Merge branch 'develop' into nanodet_c
ad-daniel Dec 6, 2022
704952f
Fix dependency
ad-daniel Dec 6, 2022
624deec
Merge branch 'develop' into nanodet_c
ManosMpampis Dec 8, 2022
ed2a13b
Merge branch 'develop' into nanodet_c
passalis Dec 8, 2022
e649c60
Update dependencies.ini
ManosMpampis Dec 9, 2022
467c1f1
update docs for new data structures and utilities of c api
Dec 12, 2022
617572d
new source, samples, utilities and test for onnx C API. The new scrip…
Dec 12, 2022
fcd4f9c
bug fixes in onnx exporting.
Dec 12, 2022
b09575b
Merge branch 'develop' into nanodet_c
ManosMpampis Dec 12, 2022
eaa9a0d
Revert "update docs for new data structures and utilities of c api"
Dec 13, 2022
953a193
Revert "bug fixes in onnx exporting."
Dec 13, 2022
bd6fb6d
Revert "Revert "bug fixes in onnx exporting.""
Dec 13, 2022
83df919
Revert "new source, samples, utilities and test for onnx C API. The n…
Dec 13, 2022
70d7543
Revert "bug fixes in onnx exporting."
Dec 13, 2022
67c78df
revert last commits, change files for cpp styles as wiki says and bet…
Dec 13, 2022
11d78d8
Merge branch 'nanodet_c' of https://github.com/opendr-eu/opendr into …
Dec 13, 2022
9a6baf0
change function name to be uniform with the others
Dec 14, 2022
13d23f9
doc for c nanodet
Dec 14, 2022
a0dbac9
Added small Json parser and installation script for easier navigation…
Dec 15, 2022
62c0266
Update projects/c_api/README.md
ManosMpampis Dec 16, 2022
8f01093
Update dependencies/install_torch_c_api.sh
ManosMpampis Dec 16, 2022
d7e6c86
Update dependencies/install_torch_c_api.sh
ManosMpampis Dec 16, 2022
9ff5c63
Update install_torch_c_api.sh
ManosMpampis Dec 16, 2022
c398d75
Update download_torch.py
ManosMpampis Dec 16, 2022
42fc691
Merge branch 'develop' into nanodet_c
ad-daniel Dec 19, 2022
30c205a
Merge branch 'develop' into nanodet_c
passalis Dec 21, 2022
ba8aa8c
Merge branch 'develop' into nanodet_c
ManosMpampis Dec 21, 2022
fbd3906
Merge branch 'develop' into nanodet_c
ad-daniel Dec 21, 2022
d320fba
Update utilities.py
ManosMpampis Dec 21, 2022
39d4c20
Fixes
ad-daniel Dec 22, 2022
5a95f14
Merge branch 'develop' into nanodet_c
ad-daniel Dec 22, 2022
3b24ab3
Fixes of suggestions
Dec 23, 2022
fb0c4fe
Fixes of suggestions
Dec 23, 2022
a191380
Fixes of suggestions
Dec 23, 2022
ad741a1
Fixes of suggestions
Dec 23, 2022
d0c0eaa
Merge branch 'develop' into nanodet_c
ManosMpampis Dec 27, 2022
f47fc17
added json parser in utilities
Dec 29, 2022
76ecd07
unnecessary use of filesystem, easier implementation in embeded
Dec 29, 2022
ebbc6d9
Merge branch 'nanodet_c' of https://github.com/opendr-eu/opendr into …
Dec 29, 2022
5f8d84e
default directory for saves change to `temp`
Jan 5, 2023
64c466f
change to warnings errors and exceptions
Jan 5, 2023
1df22cc
Transfer warnings for jit and ort simultaneously loaded from _load to…
Jan 5, 2023
2e37c40
Change naming style. All .cpp files have only CPP style naming and .c…
Jan 5, 2023
57c5903
Merge branch 'develop' of https://github.com/opendr-eu/opendr into na…
Jan 5, 2023
fdd0233
Merge branch 'develop' into nanodet_c
tsampazk Jan 6, 2023
cbb23c5
license test update
Jan 9, 2023
a7ac402
Merge branch 'develop' of https://github.com/opendr-eu/opendr into na…
Jan 9, 2023
d25a785
Merge branch 'develop' into nanodet_c
ManosMpampis Jan 9, 2023
9b87386
Merge branch 'nanodet_c' of https://github.com/opendr-eu/opendr into …
Jan 9, 2023
53a58c3
Apply suggestions from code review
ManosMpampis Jan 15, 2023
7c84d59
Apply suggestions from code review
Jan 15, 2023
cd34879
Merge branch 'nanodet_c' of https://github.com/opendr-eu/opendr into …
Jan 15, 2023
bca8c37
fixe bug to find cuda
Jan 19, 2023
4cae0ae
add automatic random colors
Jan 19, 2023
d2777a4
better implementation of optimize
Jan 19, 2023
bda2e22
add XMLBaseDataset option
Jan 19, 2023
d091dbb
train bug fix
Jan 19, 2023
6acf11d
train bug fix
Jan 19, 2023
96c86a7
tipo fix
Jan 19, 2023
42ddb48
add changes and some better namings
Jan 19, 2023
3aaffb2
Merge branch 'develop' into nanodet_c
tsampazk Jan 19, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ install_compilation_dependencies:
@+echo "#"; echo "# * Install Compilation Dependencies *"; echo "#"
@+cd dependencies; ./install.sh compilation
@+cd dependencies; ./install_onnx.sh
@+cd dependencies; ./install_torch_c_api.sh
@+make --silent -C src/opendr/control/mobile_manipulation $(TARGET) OPENDR_HOME="$(OPENDR_HOME)";
@+make --silent -C src/opendr/control/single_demo_grasp $(TARGET) OPENDR_HOME="$(OPENDR_HOME)";

Expand Down
53 changes: 53 additions & 0 deletions dependencies/install_torch_c_api.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/bin/bash

OPENDR_DEVICE="gpu"
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

if [ ! -f /usr/local/lib/libtorchvision.so ]; then
CUDA_VERSION="116"
TORCH_VERSION="1.13.0"
TORCH_DIRECTORY="/usr/local/libtorch"

VISION_VERSION="0.14.0"
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
if [[ "$OPENDR_DEVICE" == "gpu" ]]
then
echo "Downloading and installing libtorch and torchvsion (gpu support) ..."
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
GPU="on"
DEVICE="cu"${CUDA_VERSION}
CUDA_COMPILER="/usr/local/cuda/bin/nvcc"
else
echo "Downloading and installing libtorch and torchvsion (cpu-only) ..."
GPU="off"
DEVICE="cpu"
fi

# TORCH INSTALLATION
wget https://download.pytorch.org/libtorch/${DEVICE}/libtorch-cxx11-abi-shared-with-deps-${TORCH_VERSION}%2B${DEVICE}.zip --quiet
unzip -qq libtorch-cxx11-abi-shared-with-deps-${TORCH_VERSION}+${DEVICE}.zip
cd libtorch

sudo mkdir -p ${TORCH_DIRECTORY}
sudo cp -r ./* ${TORCH_DIRECTORY}
cd ..

# TORCH VISION INSTALLATION
wget https://github.com/pytorch/vision/archive/refs/tags/v${VISION_VERSION}.tar.gz --quiet
tar zxf v${VISION_VERSION}.tar.gz
cd vision-${VISION_VERSION}
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
sudo mkdir -p build
cd build
sudo cmake .. -DCMAKE_CUDA_COMPILER=${CUDA_COMPILER} -DCMAKE_PREFIX_PATH=${TORCH_DIRECTORY} -DWITH_CUDA=${GPU}
sudo make
sudo make install
cd ../..

# CLEAN
sudo rm -rf libtorch
sudo rm -rf libtorch-cxx11-abi-shared-with-deps-${TORCH_VERSION}+${DEVICE}.zip

sudo rm -rf vision-${VISION_VERSION}
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
sudo rm -rf v${VISION_VERSION}.tar.gz

sudo ldconfig

fi

163 changes: 118 additions & 45 deletions docs/reference/nanodet.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Constructor parameters:

- **model_to_use**: *{"EfficientNet_Lite0_320", "EfficientNet_Lite1_416", "EfficientNet_Lite2_512", "RepVGG_A0_416",
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
"t", "g", "m", "m_416", "m_0.5x", "m_1.5x", "m_1.5x_416", "plus_m_320", "plus_m_1.5x_320", "plus_m_416",
"plus_m_1.5x_416", "custom"}, default=plus_m_1.5x_416*\
"plus_m_1.5x_416", "custom"}, default=m*\
Specifies the model to use and the config file that contains all hyperparameters for training, evaluation and inference as the original
[Nanodet implementation](https://github.com/RangiLyu/nanodet). If you want to overwrite some of the parameters you can
put them as parameters in the learner.
Expand Down Expand Up @@ -52,7 +52,7 @@ Constructor parameters:

#### `NanodetLearner.fit`
```python
NanodetLearner.fit(self, dataset, val_dataset, logging_path, verbose, seed)
NanodetLearner.fit(self, dataset, val_dataset, logging_path, verbose, seed, local_rank)
```

This method is used for training the algorithm on a train dataset and validating on a val dataset.
Expand All @@ -71,10 +71,12 @@ Parameters:
Enables the maximum verbosity and the logger.
- **seed** : *int, default=123*\
Seed for repeatability.
- **local_rank** : *int, default=1*\
Is needed if train to multiple machines is wanted.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

#### `NanodetLearner.eval`
```python
NanodetLearner.eval(self, dataset, verbose)
NanodetLearner.eval(self, dataset, verbose, local_rank)
```

This method is used to evaluate a trained model on an evaluation dataset.
Expand All @@ -86,6 +88,8 @@ Parameters:
Object that holds the evaluation dataset.
- **verbose**: *bool, default=True*\
Enables the maximum verbosity and logger.
- **local_rank** : *int, default=1*\
Is needed if evaluation to multiple machines is wanted.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

#### `NanodetLearner.infer`
```python
Expand All @@ -105,6 +109,33 @@ Parameters:
- **verbose**: *bool, default=True*\
Enables the maximum verbosity and logger.

#### `NanodetLearner.optimize`
```python
NanodetLearner.optimize(self, export_path, initial_img=None, verbose=True, optimization="jit")
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
```

This method is used to perform jir or onnx optimizations and save a trained model with its metadata.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
If a models is already saves in export_path, the model will be loaded instead. Provided with the "export_path", it creates
the "export_path" directory, if it does already exist it try to load the optimized model in the path.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
Inside this folder, the model is saved as *"nanodet_{model_name}.pth"* for Jit models or *"nanodet_{model_name}.onnx"* for ONNX
and a metadata file *"nanodet_{model_name}.json"*.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

Note: Onnx optimization, optimize and saves only the actual model inference. This is important if the user wants to use
the model for C API. It will be needed to make a preproccess and postproccess that will work exactly the same as our python
implementation to have the exact same results.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
For C API it is recomended the Jit optimization and the example that is provided in our [c_api](../../projects/c_api/samples/nanodet/nanodet_jit_demo.c)

Parameters:

- **export_path**: *str*\
Path to save or load the optimized model.
- **initial_img**: *Image*\
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
If optimize is called for the first time is needed a dummy input of opendr Image.
- **verbose**: *bool, default=True*\
Enables the maximum verbosity and logger.
- **optimization**: *str, default="Jit"*\
It can be Jit or Onnx. It determines what kind of optimization is used.

#### `NanodetLearner.save`
```python
NanodetLearner.save(self, path, verbose)
Expand All @@ -114,6 +145,7 @@ This method is used to save a trained model with its metadata.
Provided with the path, it creates the "path" directory, if it does not already exist.
Inside this folder, the model is saved as *"nanodet_{model_name}.pth"* and a metadata file *"nanodet_{model_name}.json"*.
If the directory already exists, the *"nanodet_{model_name}.pth"* and *"nanodet_{model_name}.json"* files are overwritten.
If optimization is performed the optimized model is saved instead.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

Parameters:

Expand All @@ -129,6 +161,7 @@ NanodetLearner.load(self, path, verbose)

This method is used to load a previously saved model from its saved folder.
Loads the model from inside the directory of the path provided, using the metadata .json file included.
If optimization is performed the optimized model is loaded instead.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

Parameters:

Expand Down Expand Up @@ -171,7 +204,7 @@ Furthermore, demos on performing [training](../../projects/perception/object_det
* **Training example using an `ExternalDataset`.**

To train properly, the architecture weights must be downloaded in a predefined directory before fit is called, in this case the directory name is "predefined_examples".
Default architecture is *'plus-m-1.5x_416'*.
Default architecture is *'m'*.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
The training and evaluation dataset root should be present in the path provided, along with the annotation files.
The default COCO 2017 training data can be found [here](https://cocodataset.org/#download) (train, val, annotations).
All training parameters (optimizer, lr schedule, losses, model parameters etc.) can be changed in the model config file
Expand Down Expand Up @@ -232,58 +265,98 @@ Furthermore, demos on performing [training](../../projects/perception/object_det


if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", help="Dataset to train on", type=str, default="coco", choices=["voc", "coco"])
parser.add_argument("--data-root", help="Dataset root folder", type=str)
parser.add_argument("--model", help="Model that config file will be used", type=str)
parser.add_argument("--device", help="Device to use (cpu, cuda)", type=str, default="cuda", choices=["cuda", "cpu"])
parser.add_argument("--batch-size", help="Batch size to use for training", type=int, default=6)
parser.add_argument("--lr", help="Learning rate to use for training", type=float, default=5e-4)
parser.add_argument("--checkpoint-freq", help="Frequency in-between checkpoint saving and evaluations", type=int, default=50)
parser.add_argument("--n-epochs", help="Number of total epochs", type=int, default=300)
parser.add_argument("--resume-from", help="Epoch to load checkpoint file and resume training from", type=int, default=0)

args = parser.parse_args()

if args.dataset == 'voc':
dataset = ExternalDataset(args.data_root, 'voc')
val_dataset = ExternalDataset(args.data_root, 'voc')
elif args.dataset == 'coco':
dataset = ExternalDataset(args.data_root, 'coco')
val_dataset = ExternalDataset(args.data_root, 'coco')

nanodet = NanodetLearner(model_to_use=args.model, iters=args.n_epochs, lr=args.lr, batch_size=args.batch_size,
checkpoint_after_iter=args.checkpoint_freq, checkpoint_load_iter=args.resume_from,
device=args.device)

nanodet.download("./predefined_examples", mode="pretrained")
nanodet.load("./predefined_examples/nanodet-{}/nanodet-{}.ckpt".format(args.model, args.model), verbose=True)
nanodet.fit(dataset, val_dataset)
nanodet.save()
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", help="Dataset to train on", type=str, default="coco", choices=["voc", "coco"])
parser.add_argument("--data-root", help="Dataset root folder", type=str)
parser.add_argument("--model", help="Model that config file will be used", type=str, default="m")
parser.add_argument("--device", help="Device to use (cpu, cuda)", type=str, default="cuda", choices=["cuda", "cpu"])
parser.add_argument("--batch-size", help="Batch size to use for training", type=int, default=6)
parser.add_argument("--lr", help="Learning rate to use for training", type=float, default=5e-4)
parser.add_argument("--checkpoint-freq", help="Frequency in-between checkpoint saving and evaluations",
type=int, default=50)
parser.add_argument("--n-epochs", help="Number of total epochs", type=int, default=300)
parser.add_argument("--resume-from", help="Epoch to load checkpoint file and resume training from",
type=int, default=0)

args = parser.parse_args()
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

if args.dataset == 'voc':
dataset = ExternalDataset(args.data_root, 'voc')
val_dataset = ExternalDataset(args.data_root, 'voc')
elif args.dataset == 'coco':
dataset = ExternalDataset(args.data_root, 'coco')
val_dataset = ExternalDataset(args.data_root, 'coco')
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

nanodet = NanodetLearner(model_to_use=args.model, iters=args.n_epochs, lr=args.lr, batch_size=args.batch_size,
checkpoint_after_iter=args.checkpoint_freq, checkpoint_load_iter=args.resume_from,
device=args.device)

nanodet.download("./predefined_examples", mode="pretrained")
nanodet.load("./predefined_examples/nanodet_{}".format(args.model), verbose=True)
nanodet.fit(dataset, val_dataset)
nanodet.save()

```

* **Inference and result drawing example on a test image.**

This example shows how to perform inference on an image and draw the resulting bounding boxes using a nanodet model that is pretrained on the COCO dataset.
Moreover, inference can be used in all images in a folder, frames of a video or a webcam feedback with the provided *mode*.
In this example first is downloaded a pre-trained model as in training example and then an image to be inference.
With the same *path* parameter you can choose a folder or a video file to be used as inference. Last but not least, if 'webcam' is
used in *mode* the *camid* parameter of inference must be used to determine the webcam device in your machine.
With the *path* parameter you can choose an image file to be used as inference.

```python
import argparse
from opendr.perception.object_detection_2d import NanodetLearner

from opendr.engine.data import Image
from opendr.perception.object_detection_2d import draw_bounding_boxes

if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--device", help="Device to use (cpu, cuda)", type=str, default="cuda", choices=["cuda", "cpu"])
parser.add_argument("--model", help="Model that config file will be used", type=str)
args = parser.parse_args()
parser = argparse.ArgumentParser()
parser.add_argument("--device", help="Device to use (cpu, cuda)", type=str, default="cuda", choices=["cuda", "cpu"])
parser.add_argument("--model", help="Model that config file will be used", type=str, default='m')
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
args = parser.parse_args()

nanodet = NanodetLearner(model_to_use=args.model, device=args.device)
nanodet.download("./predefined_examples", mode="pretrained")
nanodet.load("./predefined_examples/nanodet_{}".format(args.model), verbose=True)
nanodet.download("./predefined_examples", mode="images")
img = Image.open("./predefined_examples/000000000036.jpg")
boxes = nanodet.infer(input=img)

draw_bounding_boxes(img.opencv(), boxes, class_names=nanodet.classes, show=True)
```

nanodet = NanodetLearner(model_to_use=args.model, device=args.device)
* **Optimization framework with Inference and result drawing example on a test image.**

This example shows how to perform optimization on a pretrained model and then inference and draw the resulting
bounding boxes using a nanodet model that is pretrained on the COCO dataset. In this example first is loaded a
pretrained model and then an opendr Image is used to perform optimization, in this exampel we use onnx optimization but
with `--optimization` can be used one of `[jit, onnx]`.
With the *path* parameter you can choose an image file to be used as dummy input in optimization and after in inference.
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
The optimized model will be saves in `./optimization_models` folder
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
```python
import argparse
from opendr.perception.object_detection_2d import NanodetLearner
from opendr.engine.data import Image
from opendr.perception.object_detection_2d import draw_bounding_boxes
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved

nanodet.download("./predefined_examples", mode="pretrained")
nanodet.load("./predefined_examples/nanodet-{}/nanodet-{}.ckpt".format(args.model, args.model), verbose=True)
nanodet.download("./predefined_examples", mode="images")
boxes = nanodet.infer(path="./predefined_examples/000000000036.jpg")

if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--device", help="Device to use (cpu, cuda)", type=str, default="cuda", choices=["cuda", "cpu"])
parser.add_argument("--model", help="Model that config file will be used", type=str, default='m')
parser.add_argument("--optimization", help="Optimization framework that will be used", type=str, default='onnx')
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
parser.add_argument("--path", help="Path to the dummy image that will be used for optimization and inference", type=str)
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
args = parser.parse_args()

nanodet = NanodetLearner(model_to_use=args.model, device=args.device)
nanodet.load("./predefined_examples/nanodet_{}".format(args.model), verbose=True)

# First read an openDR image from your dataset and run the optimizer:
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
img = Image.open(args.path)
nanodet.optimize("./optimization_models", img, optimization=args.optimization)

boxes = nanodet.infer(input=img)

draw_bounding_boxes(img.opencv(), boxes, class_names=nanodet.classes, show=True)
```
82 changes: 82 additions & 0 deletions include/nanodet_c.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Copyright 2020-2022 OpenDR European Project
*
* 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.
*/

#ifndef C_API_NANODET_H
#define C_API_NANODET_H

#include "opendr_utils.h"
#include "target.h"

#ifdef __cplusplus
extern "C" {
#endif

struct nanodet_model {
// Jit cpp class holder
void *net;

// Device to be used
char *device;

// Recognition threshold
float scoreThreshold;

// Model input size
int inputSize[2];

// Keep ratio flag
int keep_ratio;
};
typedef struct nanodet_model nanodet_model_t;

/**
* Loads a nanodet object detection model saved in libtorch format
* @param model_path path to the libtorch nanodet model (as exported using OpenDR library)
* @param device the device that will be used for the inference
* @param height the height of model input
* @param width the width of model input
* @param scoreThreshold a threshold for score to be infered
* @param model the loaded model
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
*/
void load_nanodet_model(char *model_path, char *device, int height, int width, float scoreThreshold, nanodet_model_t *model);

/**
* This function perform inference using a nanodet object detection model and an input image
* @param model nanodet model to be used for inference
* @param image OpenDR image
* @return vecter of OpenDR bounding box target containing the bounding boxes of the detected objectes
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
*/
opendr_detection_target_list_t infer_nanodet(opendr_image_t *image, nanodet_model_t *model);

/**
* Releases the memory allocated for a nanodet object detection model
* @param model model to be de-allocated
*/
void free_nanodet_model(nanodet_model_t *model);

/**
* draw the bounding boxes from detections in given image
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
* @param opendr_image image that has been used for inference and wanted to be printed
ManosMpampis marked this conversation as resolved.
Show resolved Hide resolved
* @param model nanodet model that has been used for inference
* @param detections output of the inference
*/
void drawBboxes(opendr_image_t *opendr_image, nanodet_model_t *model, opendr_detection_target_list_t *detections);

#ifdef __cplusplus
}
#endif

#endif // C_API_NANODET_H
Loading