Supervisely
About SuperviselyEcosystemContact usSlack
  • 💻Supervisely Developer Portal
  • 🎉Getting Started
    • Installation
    • Basics of authentication
    • Intro to Python SDK
    • Environment variables
    • Supervisely annotation format
      • Project Structure
      • Project Meta: Classes, Tags, Settings
      • Objects
      • Tags
      • Image Annotation
      • Video Annotation
      • Point Clouds Annotation
      • Point Cloud Episode Annotation
      • Volumes Annotation
    • Python SDK tutorials
      • Images
        • Images
        • Image and object tags
        • Spatial labels on images
        • Keypoints (skeletons)
        • Multispectral images
        • Multiview images
        • Advanced: Optimized Import
        • Advanced: Export
      • Videos
        • Videos
        • Video and object tags
        • Spatial labels on videos
      • Point Clouds
        • Point Clouds (LiDAR)
        • Point Cloud Episodes and object tags
        • 3D point cloud object segmentation based on sensor fusion and 2D mask guidance
        • 3D segmentation masks projection on 2D photo context image
      • Volumes
        • Volumes (DICOM)
        • Spatial labels on volumes
      • Common
        • Iterate over a project
        • Iterate over a local project
        • Progress Bar tqdm
        • Cloning projects for development
    • Command Line Interface (CLI)
      • Enterprise CLI Tool
        • Instance administration
        • Workflow automation
      • Supervisely SDK CLI
    • Connect your computer
      • Linux
      • Windows WSL
      • Troubleshooting
  • 🔥App development
    • Basics
      • Create app from any py-script
      • Configuration file
        • config.json
        • Example 1. Headless
        • Example 2. App with GUI
        • v1 - Legacy
          • Example 1. v1 Modal Window
          • Example 2. v1 app with GUI
      • Add private app
      • Add public app
      • App Compatibility
    • Apps with GUI
      • Hello World!
      • App in the Image Labeling Tool
      • App in the Video Labeling Tool
      • In-browser app in the Labeling Tool
    • Custom import app
      • Overview
      • From template - simple
      • From scratch - simple
      • From scratch GUI - advanced
      • Finding directories with specific markers
    • Custom export app
      • Overview
      • From template - simple
      • From scratch - advanced
    • Neural Network integration
      • Overview
      • Serving App
        • Introduction
        • Instance segmentation
        • Object detection
        • Semantic segmentation
        • Pose estimation
        • Point tracking
        • Object tracking
        • Mask tracking
        • Image matting
        • How to customize model inference
        • Example: Custom model inference with probability maps
      • Serving App with GUI
        • Introduction
        • How to use default GUI template
        • Default GUI template customization
        • How to create custom user interface
      • Inference API
      • Training App
        • Overview
        • Tensorboard template
        • Object detection
      • High level scheme
      • Custom inference pipeline
      • Train and predict automation model pipeline
    • Advanced
      • Advanced debugging
      • How to make your own widget
      • Tutorial - App Engine v1
        • Chapter 1 Headless
          • Part 1 — Hello world! [From your Python script to Supervisely APP]
          • Part 2 — Errors handling [Catching all bugs]
          • Part 3 — Site Packages [Customize your app]
          • Part 4 — SDK Preview [Lemons counter app]
          • Part 5 — Integrate custom tracker into Videos Annotator tool [OpenCV Tracker]
        • Chapter 2 Modal Window
          • Part 1 — Modal window [What is it?]
          • Part 2 — States and Widgets [Customize modal window]
        • Chapter 3 UI
          • Part 1 — While True Script [It's all what you need]
          • Part 2 — UI Rendering [Simplest UI Application]
          • Part 3 — APP Handlers [Handle Events and Errors]
          • Part 4 — State and Data [Mutable Fields]
          • Part 5 — Styling your app [Customizing the UI]
        • Chapter 4 Additionals
          • Part 1 — Remote Developing with PyCharm [Docker SSH Server]
      • Custom Configuration
        • Fixing SSL Certificate Errors in Supervisely
        • Fixing 400 HTTP errors when using HTTP instead of HTTPS
      • Autostart
      • Coordinate System
      • MLOps Workflow integration
    • Widgets
      • Input
        • Input
        • InputNumber
        • InputTag
        • BindedInputNumber
        • DatePicker
        • DateTimePicker
        • ColorPicker
        • TimePicker
        • ClassesMapping
        • ClassesColorMapping
      • Controls
        • Button
        • Checkbox
        • RadioGroup
        • Switch
        • Slider
        • TrainValSplits
        • FileStorageUpload
        • Timeline
        • Pagination
      • Text Elements
        • Text
        • TextArea
        • Editor
        • Copy to Clipboard
        • Markdown
        • Tooltip
        • ElementTag
        • ElementTagsList
      • Media
        • Image
        • LabeledImage
        • GridGallery
        • Video
        • VideoPlayer
        • ImagePairSequence
        • Icons
        • ObjectClassView
        • ObjectClassesList
        • ImageSlider
        • Carousel
        • TagMetaView
        • TagMetasList
        • ImageAnnotationPreview
        • ClassesMappingPreview
        • ClassesListPreview
        • TagsListPreview
        • MembersListPreview
      • Selection
        • Select
        • SelectTeam
        • SelectWorkspace
        • SelectProject
        • SelectDataset
        • SelectItem
        • SelectTagMeta
        • SelectAppSession
        • SelectString
        • Transfer
        • DestinationProject
        • TeamFilesSelector
        • FileViewer
        • Dropdown
        • Cascader
        • ClassesListSelector
        • TagsListSelector
        • MembersListSelector
        • TreeSelect
        • SelectCudaDevice
      • Thumbnails
        • ProjectThumbnail
        • DatasetThumbnail
        • VideoThumbnail
        • FolderThumbnail
        • FileThumbnail
      • Status Elements
        • Progress
        • NotificationBox
        • DoneLabel
        • DialogMessage
        • TaskLogs
        • Badge
        • ModelInfo
        • Rate
        • CircleProgress
      • Layouts and Containers
        • Card
        • Container
        • Empty
        • Field
        • Flexbox
        • Grid
        • Menu
        • OneOf
        • Sidebar
        • Stepper
        • RadioTabs
        • Tabs
        • TabsDynamic
        • ReloadableArea
        • Collapse
        • Dialog
        • IFrame
      • Tables
        • Table
        • ClassicTable
        • RadioTable
        • ClassesTable
        • RandomSplitsTable
        • FastTable
      • Charts and Plots
        • LineChart
        • GridChart
        • HeatmapChart
        • ApexChart
        • ConfusionMatrix
        • LinePlot
        • GridPlot
        • ScatterChart
        • TreemapChart
        • PieChart
      • Compare Data
        • MatchDatasets
        • MatchTagMetas
        • MatchObjClasses
        • ClassBalance
        • CompareAnnotations
      • Widgets demos on github
  • 😎Advanced user guide
    • Objects binding
    • Automate with Python SDK & API
      • Start and stop app
      • User management
      • Labeling Jobs
  • 🖥️UI widgets
    • Element UI library
    • Supervisely UI widgets
    • Apexcharts - modern & interactive charts
    • Plotly graphing library
  • 📚API References
    • REST API Reference
    • Python SDK Reference
Powered by GitBook
On this page
  • Introduction
  • Getting started
  • Python script
  • Implementation details
  • Overall structure
  • Step-by-step implementation
  • Run and debug
  • Local debug
  • Debug in Supervisely platform
  • Release your code as a Supervisely App.
  • Repository structure
  • App configuration

Was this helpful?

Edit on GitHub
  1. App development
  2. Neural Network integration
  3. Serving App

Instance segmentation

Step-by-step tutorial of how to integrate custom instance segmentation neural network into Supervisely platform on the example of detectron2.

PreviousIntroductionNextObject detection

Last updated 6 months ago

Was this helpful?

Introduction

In this tutorial you will learn how to integrate your custom instance segmentation model into Supervisely by creating a simple serving app. As an example, we will use repository, which implements a set of detection models.

Getting started

Step 1. Prepare ~/supervisely.env file with credentials.

Step 2. Clone with source code and create .

git clone https://github.com/supervisely-ecosystem/integrate-inst-seg-model
cd integrate-inst-seg-model
./create_venv.sh

Step 3. Open the repository directory in Visual Studio Code.

code -r .

Step 4. Run debug for script src/main.py

Python script

The integration script is simple:

  1. Automatically downloads NN weights to ./my_model folder

  2. Loads model on the CPU or GPU device

  3. Runs inference on a demo image

  4. Visualizes predictions on top of the input image

Implementation details

To integrate your model, you need to subclass sly.nn.inference.InstanceSegmentation and implement 3 methods:

  • load_on_device method for downloading the weights and initializing the model on a specific device. Takes a model_dir argument, that is a directory for all model files (like configs, weights, etc). The second argument is a device - a torch.device like cuda:0, cpu.

  • get_classes method should return a list of class names (strings) that model can predict.

  • predict. The core implementation of a model inference. It takes a path to an image and inference settings as arguments, applies the model inference to the image and returns a list of predictions (which are sly.nn.PredictionMask objects).

Overall structure

The overall structure of the class we will implement is looking like this:

class MyModel(sly.nn.inference.InstanceSegmentation):
    def load_on_device(
        self,
        model_dir: str,
        device: Literal["cpu", "cuda", "cuda:0", "cuda:1", "cuda:2", "cuda:3"] = "cpu",
    ):
        # preparing the model: model instantiating, downloading weights, loading it on device.
        pass

    def get_classes(self) -> List[str]:
        # returns a list of supported classes, e.g. ["cat", "dog", ...]
        # ...
        return class_names

    def predict(self, image_path: str, settings: Dict[str, Any]) -> List[sly.nn.PredictionMask]:
        # the inference of a model here
        # ...
        return prediction

The superclass has a serve() method. For running the code on the Supervisely platform, m.serve() method should be executed:

if sly.is_production():
    m.serve()
else:
    # ...

And here is the beauty comes in. The method serve() internally handles everything and deploys your model as a REST API service on the Supervisely platform. It means that other applications are able to communicate with your model and get predictions from it.

So let's implement the class.

Step-by-step implementation

Defining imports and global variables

import os
from typing_extensions import Literal
from typing import List, Any, Dict
import cv2
from dotenv import load_dotenv
import torch
import supervisely as sly

from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog


load_dotenv("local.env")
load_dotenv(os.path.expanduser("~/supervisely.env"))

weights_url = "https://dl.fbaipublicfiles.com/detectron2/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl"
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using device:", device)

1. load_on_device

The following code downloads model weights, creates the model according to config my_model/model_info.json (which will instantiate one of detectron2 architecture). Also it will keep the model as a self.predictor and classes as self.class_names for further use:

class MyModel(sly.nn.inference.InstanceSegmentation):
    def load_on_device(
            self,
            model_dir: str,
            device: Literal["cpu", "cuda", "cuda:0", "cuda:1", "cuda:2", "cuda:3"] = "cpu",
        ):
            weights_path = self.download(weights_url)
            model_info = sly.json.load_json_file(os.path.join(model_dir, "model_info.json"))
            architecture_name = model_info["architecture"]
            cfg = get_cfg()
            cfg.merge_from_file(model_zoo.get_config_file(architecture_name))
            cfg.MODEL.DEVICE = device  # learn more in torch.device
            cfg.MODEL.WEIGHTS = weights_path
            self.predictor = DefaultPredictor(cfg)
            self.class_names = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]).get("thing_classes")
            print(f"✅ Model has been successfully loaded on {device.upper()} device")

Here we are downloading the model weights by url, but it can be also downloaded by path in Supervisely Team Files. You can even pass a path to folder with the model, then an entire folder will be downloaded.

2. get_classes

Simply returns previously saved class_names:

    def get_classes(self) -> List[str]:
        return self.class_names  # e.g. ["cat", "dog", ...]

3. predict

The core method for model inference. Here we are reading an image and getting an inference of the model. The code here is usually borrowed from the framework or the model you use, that is detectron2 in our case. It let us simply use self.predictor(image). Then we wrap model predictions into sly.nn.PredictionMask and do some post-processing steps.

    def predict(self, image_path: str, settings: Dict[str, Any]) -> List[sly.nn.PredictionMask]:
        confidence_threshold = settings.get("confidence_threshold", 0.5)
        image = cv2.imread(image_path)  # BGR

        outputs = self.predictor(image)  # get predictions from Detectron2 model
        pred_classes = outputs["instances"].pred_classes.detach().numpy()
        pred_class_names = [self.class_names[pred_class] for pred_class in pred_classes]
        pred_scores = outputs["instances"].scores.detach().numpy().tolist()
        pred_masks = outputs["instances"].pred_masks.detach().numpy()

        results = []
        for score, class_name, mask in zip(pred_scores, pred_class_names, pred_masks):
            # filter predictions by confidence
            if score >= confidence_threshold:
                results.append(sly.nn.PredictionMask(class_name, mask, score))
        return results

It must return exactly a list of sly.nn.PredictionMask objects for compatibility with Supervisely. Your code should just wrap the prediction: sly.nn.PredictionMask(class_name, mask, score), where the mask is a np.array prediction mask and the score is a float confidence_score.

Usage of our class

Once the class is created, here we initialize it and get one test prediction for debugging.

model_dir = "my_model"  # model weights will be downloaded into this dir
settings = {"confidence_threshold": 0.7}

m = MyModel(model_dir=model_dir, custom_inference_settings=settings)
m.load_on_device(model_dir=model_dir, device=device)

if sly.is_production():
    # this code block is running on Supervisely platform in production
    # just ignore it during development
    m.serve()
else:
    # for local development and debugging
    image_path = "./demo_data/image_01.jpg"
    results = m.predict(image_path, settings)
    vis_path = "./demo_data/image_01_prediction.jpg"
    m.visualize(results, image_path, vis_path)
    print(f"predictions and visualization have been saved: {vis_path}")

Here are the input image and output predictions:

Input
Output

Run and debug

The beauty of this class is that you can easily debug your code locally in your favorite IDE.

For now, we recommend using Visual Studio Code IDE, because our repositories have prepared settings for convenient debugging in VSCode. It is the easiest way to start.

Local debug

You can run the code locally for debugging. For Visual Studio Code we've created a launch.json config file that can be selected:

Debug in Supervisely platform

Once the code seems working locally, it's time to test the code right in the Supervisely platform as a debugging app. For that:

  1. If you develop in a Docker container, you should run the container with --cap_add=NET_ADMIN option.

  2. Install sudo apt-get install wireguard iproute2.

  3. Define your TEAM_ID in the local.env file. Actually there are other env variables that is needed, but they are already provided in ./vscode/launch.json for you.

  4. Switch the launch.json config to the Advanced debug in Supervisely platform:

  1. Run the code.

✅ It will deploy the model in the Supervisely platform as a regular serving App that is able to communicate with all others app in the platform:

Release your code as a Supervisely App.

Once you've tested the code, it's time to release it into the platform. It can be released as an App that shared with the all Supervisely community, or as your own private App.

In this tutorial we'll quickly observe the key concepts of our app.

Repository structure

.
├── README.md
├── config.json
├── create_venv.sh
├── requirements.txt
├── demo_data
│   ├── image_01.jpg
│   └── image_01_prediction.jpg
├── docker
│   ├── Dockerfile
│   └── publish.sh
├── local.env
├── my_model
│   └── model_info.json
└── src
    └── main.py

Explanation:

  • src/main.py - main inference script

  • my_model - directory with model weights and additional config files

  • demo_data - directory with demo image for inference

  • README.md - readme of your application, it is the main page of an application in Ecosystem with some images, videos, and how-to-use guides

  • config.json - configuration of the Supervisely application, which defines the name and description of the app, its context menu, icon, poster, and running settings

  • create_venv.sh - creates a virtual environment, installs detectron2 framework, includes the support of Apple CPUs (m1 / m2 ...)

  • requirements.txt - all packages needed for debugging

  • local.env - file with variables used for debugging

  • docker - directory with the custom Dockerfile for this application and the script that builds it and publishes it to the docker registry

App configuration

{
  "type": "app",
  "version": "2.0.0",
  "name": "Serve custom instance segmentation model",
  "description": "Demo app for integrating your custom instance segmentation model",
  "categories": [
    "neural network",
    "images",
    "videos",
    "instance segmentation",
    "segmentation & tracking",
    "serve",
    "development"
  ],
  "session_tags": ["deployed_nn"],
  "need_gpu": true,
  "community_agent": false,
  "docker_image": "supervisely/detectron2-demo:1.0.3",
  "entrypoint": "python -m uvicorn src.main:m.app --host 0.0.0.0 --port 8000",
  "port": 8000,
  "headless": true
}

Here is the explanation for the fields:

  • type - type of the module in Supervisely Ecosystem

  • version - version of Supervisely App Engine. Just keep it by default

  • name - the name of the application

  • description - the description of the application

  • categories - these tags are used to place the application in the correct category in Ecosystem.

  • session_tags - these tags will be assigned to every running session of the application. They can be used by other apps to find and filter all running sessions

  • "need_gpu": true - should be true if you want to use any cuda devices.

  • "community_agent": false - this means that this app can not be run on the agents started by Supervisely team, so users have to connect their own computers and run the app only on their own agents. Only applicable in Community Edition. Enterprise customers use their private instances so they can ignore current option

  • docker_image - Docker container will be started from the defined Docker image, github repository will be downloaded and mounted inside the container.

  • entrypoint - the command that starts our application in a container

  • port - port inside the container

  • "headless": true means that the app has no User Interface

The entire integration Python script takes only 👍 90 lines of code (including comments) and can be found in for this tutorial.

In the code below a custom_inference_settings is used. It allows us to provide a custom settings that could be used in predict() (See more in )

Local debug
Advanced Debug in Supervisely
Develop and Debug

Now you can use apps like , with your deployed model.

Or get the model inference via Python API with the help of sly.nn.inference.Session class just in one line of code. See .

Refer to for all releasing details. For a private app check also .

The structure of is the following:

App configuration is stored in config.json file. A detailed explanation of all possible fields is covered in this . Let's check the config for our current app:

🔥
GitHub repository
Customized Inference Tutorial
Apply NN to Images
Apply NN to videos
Inference API Tutorial
How to Release your App
Private App Tutorial
our GitHub repository
Configuration Tutorial
Facebook's detectron2
repository
Virtual Environment
Learn more here.