Spaces:
Sleeping
Sleeping
dev-deg commited on
Commit ·
ecd06a9
1
Parent(s): 2748d4c
Added option to select model version and execution time. Groundwork to run ONNX models started but still some work todo.
Browse files- .gitignore +1 -0
- ambulant.yaml +6 -0
- app.py +7 -6
- inferencing.py +15 -42
- latest.pt +0 -0
- onnx_inf.py +323 -0
- pytorch_inf.py +48 -0
- requirements.txt +5 -1
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
.env
|
ambulant.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
path: D:/01_Projects/AMBULANT/dataset
|
| 2 |
+
train: train # train images (relative to 'path') 128 images
|
| 3 |
+
val: valid # val images (relative to 'path') 128 images
|
| 4 |
+
|
| 5 |
+
nc: 29
|
| 6 |
+
names: ['Asparagopsis taxiformis', 'CCS', 'Centrostephanus longispinus', 'Coarse sand', 'Crambe crambe', 'Cymodocea nodosa', 'Dictyopteris polypodioides', 'Halophila stipulacea', 'Hard bed and rock', 'Hermodice carunculata', 'Jania rubens', 'Lithophyllum incrustans', 'Padina pavonica', 'Peyssonnelia sp.', 'Posidonia oceanica', 'Protula sp.', 'Sand', 'Sarcotragus spinosulus', 'Sargassum vulgare', 'Scalarispongia scalaris', 'Stones and Pebbles', 'Zonaria tournefortii', 'Chondrilla nucula', 'Codium bursa', 'Dictyota dichotoma', 'Liagora viscida', 'Lophocladia lallemandii', 'Stones and pebbles', 'Ulva compressa']
|
app.py
CHANGED
|
@@ -34,15 +34,16 @@ color_map_dict = {
|
|
| 34 |
|
| 35 |
iface = gr.Interface(
|
| 36 |
fn=run_inference,
|
| 37 |
-
inputs="
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
| 39 |
gradio.DataFrame(label="Predicted Benthic Habitat",headers=["Prediction", "Confidence"]),
|
| 40 |
gradio.DataFrame(label="Habitat Confidence Values",headers=["Classification", "Confidence"]),
|
| 41 |
gradio.Image(label="Instance Segmentation Result"),
|
| 42 |
gradio.DataFrame(label="Identified Classes Confidence Values",headers=["Classification", "Confidence"])],
|
| 43 |
-
description="Last updated:
|
| 44 |
title="AMBULANT Benthic Habitat Identification System"
|
| 45 |
)
|
| 46 |
-
iface.launch()
|
| 47 |
-
|
| 48 |
-
|
|
|
|
| 34 |
|
| 35 |
iface = gr.Interface(
|
| 36 |
fn=run_inference,
|
| 37 |
+
inputs=[gradio.Image(label="Image to Evaluate"),
|
| 38 |
+
gradio.Dropdown(label="Model version",choices=["v1.0.0", "v1.1.0", "v1.2.0"], value="v1.2.0"),
|
| 39 |
+
gradio.Dropdown(label="Inference strategy",choices=["Pytorch"], value="Pytorch")],
|
| 40 |
+
outputs=[gradio.Textbox(label="Execution duration"),
|
| 41 |
+
gradio.Annotatedimage(label="Interactive Object Detection",color_map=color_map_dict),
|
| 42 |
gradio.DataFrame(label="Predicted Benthic Habitat",headers=["Prediction", "Confidence"]),
|
| 43 |
gradio.DataFrame(label="Habitat Confidence Values",headers=["Classification", "Confidence"]),
|
| 44 |
gradio.Image(label="Instance Segmentation Result"),
|
| 45 |
gradio.DataFrame(label="Identified Classes Confidence Values",headers=["Classification", "Confidence"])],
|
| 46 |
+
description="Last updated: 17th January 2024",
|
| 47 |
title="AMBULANT Benthic Habitat Identification System"
|
| 48 |
)
|
| 49 |
+
iface.launch()
|
|
|
|
|
|
inferencing.py
CHANGED
|
@@ -1,51 +1,24 @@
|
|
| 1 |
-
from
|
| 2 |
-
import pandas as pd
|
| 3 |
-
from habitat_classification import classify_habitat, get_inconclusive
|
| 4 |
from huggingface_hub import hf_hub_download
|
| 5 |
import os
|
| 6 |
import dotenv
|
| 7 |
|
| 8 |
-
|
| 9 |
dotenv.load_dotenv()
|
| 10 |
hf_tk = os.getenv('HF_AT')
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
for result in results:
|
| 16 |
-
if result.boxes.data.nelement() != 0:
|
| 17 |
-
for detection in result.boxes.data:
|
| 18 |
-
x1, y1, x2, y2, conf, cls = detection.cpu().numpy()
|
| 19 |
-
class_name = result.names[int(cls)]
|
| 20 |
-
detections.append([class_name, conf])
|
| 21 |
-
annotations.append(((int(x1), int(y1), int(x2), int(y2)), class_name))
|
| 22 |
-
outframe = results[0].plot()
|
| 23 |
-
return frame, outframe, annotations, pd.DataFrame(detections, columns=["Class", "Confidence"])
|
| 24 |
-
|
| 25 |
-
print("No detections")
|
| 26 |
-
return frame, [], []
|
| 27 |
-
|
| 28 |
-
def process_image(input_image):
|
| 29 |
-
results = model(input_image)
|
| 30 |
-
return display_detections(input_image, results)
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
habitat_res = classify_habitat(class_names)
|
| 38 |
-
return habitat_res[0], habitat_res[1]
|
| 39 |
|
| 40 |
-
def run_inference(input_image):
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
habitat, probabilities = get_habitat_data(detections['Class'].tolist())
|
| 47 |
-
return (frame, annotations), habitat, probabilities, outframe, detections
|
| 48 |
-
# Load YOLO model
|
| 49 |
-
raw_model = hf_hub_download(repo_id="dev-deg/Ambulant_1.0", filename="latest.pt",use_auth_token=hf_tk)
|
| 50 |
-
model = YOLO(raw_model)
|
| 51 |
-
model.conf = 0.2
|
|
|
|
| 1 |
+
from ambulant.pytorch_inf import run_pytorch_inference
|
|
|
|
|
|
|
| 2 |
from huggingface_hub import hf_hub_download
|
| 3 |
import os
|
| 4 |
import dotenv
|
| 5 |
|
|
|
|
| 6 |
dotenv.load_dotenv()
|
| 7 |
hf_tk = os.getenv('HF_AT')
|
| 8 |
|
| 9 |
+
raw_model_v1_0 = hf_hub_download(repo_id="dev-deg/ambulant_pt_v1.0.0", filename="model.pt",use_auth_token=hf_tk)
|
| 10 |
+
raw_model_v1_1 = hf_hub_download(repo_id="dev-deg/ambulant_pt_v1.1.0", filename="model.pt",use_auth_token=hf_tk)
|
| 11 |
+
raw_model_v1_2 = hf_hub_download(repo_id="dev-deg/ambulant_pt_v1.2.0", filename="model.pt",use_auth_token=hf_tk)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
pt_models = {
|
| 14 |
+
"v1.0.0": raw_model_v1_0,
|
| 15 |
+
"v1.1.0": raw_model_v1_1,
|
| 16 |
+
"v1.2.0": raw_model_v1_2
|
| 17 |
+
}
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
def run_inference(input_image, model_version, model_type):
|
| 20 |
+
if input_image is None:
|
| 21 |
+
return None, None, None, None, None, None
|
| 22 |
+
if model_type == "Pytorch":
|
| 23 |
+
return run_pytorch_inference(input_image, pt_models[model_version])
|
| 24 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
latest.pt
DELETED
|
File without changes
|
onnx_inf.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
| 2 |
+
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
import onnxruntime as ort
|
| 6 |
+
|
| 7 |
+
from ultralytics.utils import ASSETS, yaml_load
|
| 8 |
+
from ultralytics.utils.checks import check_yaml
|
| 9 |
+
from ultralytics.utils.plotting import Colors
|
| 10 |
+
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
class YOLOv8SegONNX:
|
| 14 |
+
"""YOLOv8 segmentation model."""
|
| 15 |
+
|
| 16 |
+
def __init__(self, onnx_model):
|
| 17 |
+
"""
|
| 18 |
+
Initialization.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
onnx_model (str): Path to the ONNX model.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
# Build Ort session
|
| 25 |
+
self.session = ort.InferenceSession(
|
| 26 |
+
onnx_model,
|
| 27 |
+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"]
|
| 28 |
+
if ort.get_device() == "GPU"
|
| 29 |
+
else ["CPUExecutionProvider"],
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Numpy dtype: support both FP32 and FP16 onnx model
|
| 33 |
+
self.ndtype = np.half if self.session.get_inputs()[0].type == "tensor(float16)" else np.single
|
| 34 |
+
|
| 35 |
+
# Get model width and height(YOLOv8-seg only has one input)
|
| 36 |
+
self.model_height, self.model_width = [x.shape for x in self.session.get_inputs()][0][-2:]
|
| 37 |
+
|
| 38 |
+
# Load COCO class names
|
| 39 |
+
self.classes = yaml_load(check_yaml("ambulant.yaml"))["names"]
|
| 40 |
+
|
| 41 |
+
# Create color palette
|
| 42 |
+
self.color_palette = Colors()
|
| 43 |
+
|
| 44 |
+
def __call__(self, im0, conf_threshold=0.4, iou_threshold=0.45, nm=32):
|
| 45 |
+
"""
|
| 46 |
+
The whole pipeline: pre-process -> inference -> post-process.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
im0 (Numpy.ndarray): original input image.
|
| 50 |
+
conf_threshold (float): confidence threshold for filtering predictions.
|
| 51 |
+
iou_threshold (float): iou threshold for NMS.
|
| 52 |
+
nm (int): the number of masks.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
boxes (List): list of bounding boxes.
|
| 56 |
+
segments (List): list of segments.
|
| 57 |
+
masks (np.ndarray): [N, H, W], output masks.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
# Pre-process
|
| 61 |
+
im, ratio, (pad_w, pad_h) = self.preprocess(im0)
|
| 62 |
+
|
| 63 |
+
# Ort inference
|
| 64 |
+
preds = self.session.run(None, {self.session.get_inputs()[0].name: im})
|
| 65 |
+
|
| 66 |
+
# Post-process
|
| 67 |
+
boxes, segments, masks = self.postprocess(
|
| 68 |
+
preds,
|
| 69 |
+
im0=im0,
|
| 70 |
+
ratio=ratio,
|
| 71 |
+
pad_w=pad_w,
|
| 72 |
+
pad_h=pad_h,
|
| 73 |
+
conf_threshold=conf_threshold,
|
| 74 |
+
iou_threshold=iou_threshold,
|
| 75 |
+
nm=nm,
|
| 76 |
+
)
|
| 77 |
+
return boxes, segments, masks
|
| 78 |
+
|
| 79 |
+
def preprocess(self, img):
|
| 80 |
+
"""
|
| 81 |
+
Pre-processes the input image.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
img (Numpy.ndarray): image about to be processed.
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
img_process (Numpy.ndarray): image preprocessed for inference.
|
| 88 |
+
ratio (tuple): width, height ratios in letterbox.
|
| 89 |
+
pad_w (float): width padding in letterbox.
|
| 90 |
+
pad_h (float): height padding in letterbox.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
# Resize and pad input image using letterbox() (Borrowed from Ultralytics)
|
| 94 |
+
shape = img.shape[:2] # original image shape
|
| 95 |
+
new_shape = (self.model_height, self.model_width)
|
| 96 |
+
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
|
| 97 |
+
ratio = r, r
|
| 98 |
+
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
|
| 99 |
+
pad_w, pad_h = (new_shape[1] - new_unpad[0]) / 2, (new_shape[0] - new_unpad[1]) / 2 # wh padding
|
| 100 |
+
if shape[::-1] != new_unpad: # resize
|
| 101 |
+
img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
|
| 102 |
+
top, bottom = int(round(pad_h - 0.1)), int(round(pad_h + 0.1))
|
| 103 |
+
left, right = int(round(pad_w - 0.1)), int(round(pad_w + 0.1))
|
| 104 |
+
img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114))
|
| 105 |
+
|
| 106 |
+
# Transforms: HWC to CHW -> BGR to RGB -> div(255) -> contiguous -> add axis(optional)
|
| 107 |
+
img = np.ascontiguousarray(np.einsum("HWC->CHW", img)[::-1], dtype=self.ndtype) / 255.0
|
| 108 |
+
img_process = img[None] if len(img.shape) == 3 else img
|
| 109 |
+
return img_process, ratio, (pad_w, pad_h)
|
| 110 |
+
|
| 111 |
+
def postprocess(self, preds, im0, ratio, pad_w, pad_h, conf_threshold, iou_threshold, nm=32):
|
| 112 |
+
"""
|
| 113 |
+
Post-process the prediction.
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
preds (Numpy.ndarray): predictions come from ort.session.run().
|
| 117 |
+
im0 (Numpy.ndarray): [h, w, c] original input image.
|
| 118 |
+
ratio (tuple): width, height ratios in letterbox.
|
| 119 |
+
pad_w (float): width padding in letterbox.
|
| 120 |
+
pad_h (float): height padding in letterbox.
|
| 121 |
+
conf_threshold (float): conf threshold.
|
| 122 |
+
iou_threshold (float): iou threshold.
|
| 123 |
+
nm (int): the number of masks.
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
boxes (List): list of bounding boxes.
|
| 127 |
+
segments (List): list of segments.
|
| 128 |
+
masks (np.ndarray): [N, H, W], output masks.
|
| 129 |
+
"""
|
| 130 |
+
x, protos = preds[0], preds[1] # Two outputs: predictions and protos
|
| 131 |
+
|
| 132 |
+
# Transpose the first output: (Batch_size, xywh_conf_cls_nm, Num_anchors) -> (Batch_size, Num_anchors, xywh_conf_cls_nm)
|
| 133 |
+
x = np.einsum("bcn->bnc", x)
|
| 134 |
+
|
| 135 |
+
# Predictions filtering by conf-threshold
|
| 136 |
+
x = x[np.amax(x[..., 4:-nm], axis=-1) > conf_threshold]
|
| 137 |
+
|
| 138 |
+
# Create a new matrix which merge these(box, score, cls, nm) into one
|
| 139 |
+
# For more details about `numpy.c_()`: https://numpy.org/doc/1.26/reference/generated/numpy.c_.html
|
| 140 |
+
x = np.c_[x[..., :4], np.amax(x[..., 4:-nm], axis=-1), np.argmax(x[..., 4:-nm], axis=-1), x[..., -nm:]]
|
| 141 |
+
|
| 142 |
+
# NMS filtering
|
| 143 |
+
x = x[cv2.dnn.NMSBoxes(x[:, :4], x[:, 4], conf_threshold, iou_threshold)]
|
| 144 |
+
|
| 145 |
+
# Decode and return
|
| 146 |
+
if len(x) > 0:
|
| 147 |
+
# Bounding boxes format change: cxcywh -> xyxy
|
| 148 |
+
x[..., [0, 1]] -= x[..., [2, 3]] / 2
|
| 149 |
+
x[..., [2, 3]] += x[..., [0, 1]]
|
| 150 |
+
|
| 151 |
+
# Rescales bounding boxes from model shape(model_height, model_width) to the shape of original image
|
| 152 |
+
x[..., :4] -= [pad_w, pad_h, pad_w, pad_h]
|
| 153 |
+
x[..., :4] /= min(ratio)
|
| 154 |
+
|
| 155 |
+
# Bounding boxes boundary clamp
|
| 156 |
+
x[..., [0, 2]] = x[:, [0, 2]].clip(0, im0.shape[1])
|
| 157 |
+
x[..., [1, 3]] = x[:, [1, 3]].clip(0, im0.shape[0])
|
| 158 |
+
|
| 159 |
+
# Process masks
|
| 160 |
+
masks = self.process_mask(protos[0], x[:, 6:], x[:, :4], im0.shape)
|
| 161 |
+
|
| 162 |
+
# Masks -> Segments(contours)
|
| 163 |
+
segments = self.masks2segments(masks)
|
| 164 |
+
return x[..., :6], segments, masks # boxes, segments, masks
|
| 165 |
+
else:
|
| 166 |
+
return [], [], []
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
def masks2segments(masks):
|
| 170 |
+
"""
|
| 171 |
+
It takes a list of masks(n,h,w) and returns a list of segments(n,xy) (Borrowed from
|
| 172 |
+
https://github.com/ultralytics/ultralytics/blob/465df3024f44fa97d4fad9986530d5a13cdabdca/ultralytics/utils/ops.py#L750)
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
masks (numpy.ndarray): the output of the model, which is a tensor of shape (batch_size, 160, 160).
|
| 176 |
+
|
| 177 |
+
Returns:
|
| 178 |
+
segments (List): list of segment masks.
|
| 179 |
+
"""
|
| 180 |
+
segments = []
|
| 181 |
+
for x in masks.astype("uint8"):
|
| 182 |
+
c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[0] # CHAIN_APPROX_SIMPLE
|
| 183 |
+
if c:
|
| 184 |
+
c = np.array(c[np.array([len(x) for x in c]).argmax()]).reshape(-1, 2)
|
| 185 |
+
else:
|
| 186 |
+
c = np.zeros((0, 2)) # no segments found
|
| 187 |
+
segments.append(c.astype("float32"))
|
| 188 |
+
return segments
|
| 189 |
+
|
| 190 |
+
@staticmethod
|
| 191 |
+
def crop_mask(masks, boxes):
|
| 192 |
+
"""
|
| 193 |
+
It takes a mask and a bounding box, and returns a mask that is cropped to the bounding box. (Borrowed from
|
| 194 |
+
https://github.com/ultralytics/ultralytics/blob/465df3024f44fa97d4fad9986530d5a13cdabdca/ultralytics/utils/ops.py#L599)
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
masks (Numpy.ndarray): [n, h, w] tensor of masks.
|
| 198 |
+
boxes (Numpy.ndarray): [n, 4] tensor of bbox coordinates in relative point form.
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
(Numpy.ndarray): The masks are being cropped to the bounding box.
|
| 202 |
+
"""
|
| 203 |
+
n, h, w = masks.shape
|
| 204 |
+
x1, y1, x2, y2 = np.split(boxes[:, :, None], 4, 1)
|
| 205 |
+
r = np.arange(w, dtype=x1.dtype)[None, None, :]
|
| 206 |
+
c = np.arange(h, dtype=x1.dtype)[None, :, None]
|
| 207 |
+
return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))
|
| 208 |
+
|
| 209 |
+
def process_mask(self, protos, masks_in, bboxes, im0_shape):
|
| 210 |
+
"""
|
| 211 |
+
Takes the output of the mask head, and applies the mask to the bounding boxes. This produces masks of higher quality
|
| 212 |
+
but is slower. (Borrowed from https://github.com/ultralytics/ultralytics/blob/465df3024f44fa97d4fad9986530d5a13cdabdca/ultralytics/utils/ops.py#L618)
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
protos (numpy.ndarray): [mask_dim, mask_h, mask_w].
|
| 216 |
+
masks_in (numpy.ndarray): [n, mask_dim], n is number of masks after nms.
|
| 217 |
+
bboxes (numpy.ndarray): bboxes re-scaled to original image shape.
|
| 218 |
+
im0_shape (tuple): the size of the input image (h,w,c).
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
(numpy.ndarray): The upsampled masks.
|
| 222 |
+
"""
|
| 223 |
+
c, mh, mw = protos.shape
|
| 224 |
+
masks = np.matmul(masks_in, protos.reshape((c, -1))).reshape((-1, mh, mw)).transpose(1, 2, 0) # HWN
|
| 225 |
+
masks = np.ascontiguousarray(masks)
|
| 226 |
+
masks = self.scale_mask(masks, im0_shape) # re-scale mask from P3 shape to original input image shape
|
| 227 |
+
masks = np.einsum("HWN -> NHW", masks) # HWN -> NHW
|
| 228 |
+
masks = self.crop_mask(masks, bboxes)
|
| 229 |
+
return np.greater(masks, 0.5)
|
| 230 |
+
|
| 231 |
+
@staticmethod
|
| 232 |
+
def scale_mask(masks, im0_shape, ratio_pad=None):
|
| 233 |
+
"""
|
| 234 |
+
Takes a mask, and resizes it to the original image size. (Borrowed from
|
| 235 |
+
https://github.com/ultralytics/ultralytics/blob/465df3024f44fa97d4fad9986530d5a13cdabdca/ultralytics/utils/ops.py#L305)
|
| 236 |
+
|
| 237 |
+
Args:
|
| 238 |
+
masks (np.ndarray): resized and padded masks/images, [h, w, num]/[h, w, 3].
|
| 239 |
+
im0_shape (tuple): the original image shape.
|
| 240 |
+
ratio_pad (tuple): the ratio of the padding to the original image.
|
| 241 |
+
|
| 242 |
+
Returns:
|
| 243 |
+
masks (np.ndarray): The masks that are being returned.
|
| 244 |
+
"""
|
| 245 |
+
im1_shape = masks.shape[:2]
|
| 246 |
+
if ratio_pad is None: # calculate from im0_shape
|
| 247 |
+
gain = min(im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1]) # gain = old / new
|
| 248 |
+
pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (im1_shape[0] - im0_shape[0] * gain) / 2 # wh padding
|
| 249 |
+
else:
|
| 250 |
+
pad = ratio_pad[1]
|
| 251 |
+
|
| 252 |
+
# Calculate tlbr of mask
|
| 253 |
+
top, left = int(round(pad[1] - 0.1)), int(round(pad[0] - 0.1)) # y, x
|
| 254 |
+
bottom, right = int(round(im1_shape[0] - pad[1] + 0.1)), int(round(im1_shape[1] - pad[0] + 0.1))
|
| 255 |
+
if len(masks.shape) < 2:
|
| 256 |
+
raise ValueError(f'"len of masks shape" should be 2 or 3, but got {len(masks.shape)}')
|
| 257 |
+
masks = masks[top:bottom, left:right]
|
| 258 |
+
masks = cv2.resize(
|
| 259 |
+
masks, (im0_shape[1], im0_shape[0]), interpolation=cv2.INTER_LINEAR
|
| 260 |
+
) # INTER_CUBIC would be better
|
| 261 |
+
if len(masks.shape) == 2:
|
| 262 |
+
masks = masks[:, :, None]
|
| 263 |
+
return masks
|
| 264 |
+
|
| 265 |
+
def draw_and_visualize(self, im, bboxes, segments, vis=False, save=True):
|
| 266 |
+
"""
|
| 267 |
+
Draw and visualize results.
|
| 268 |
+
|
| 269 |
+
Args:
|
| 270 |
+
im (np.ndarray): original image, shape [h, w, c].
|
| 271 |
+
bboxes (numpy.ndarray): [n, 4], n is number of bboxes.
|
| 272 |
+
segments (List): list of segment masks.
|
| 273 |
+
vis (bool): imshow using OpenCV.
|
| 274 |
+
save (bool): save image annotated.
|
| 275 |
+
|
| 276 |
+
Returns:
|
| 277 |
+
None
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
# Draw rectangles and polygons
|
| 281 |
+
im_canvas = im.copy()
|
| 282 |
+
for (*box, conf, cls_), segment in zip(bboxes, segments):
|
| 283 |
+
# draw contour and fill mask
|
| 284 |
+
cv2.polylines(im, np.int32([segment]), True, (255, 255, 255), 2) # white borderline
|
| 285 |
+
cv2.fillPoly(im_canvas, np.int32([segment]), self.color_palette(int(cls_), bgr=True))
|
| 286 |
+
|
| 287 |
+
# draw bbox rectangle
|
| 288 |
+
cv2.rectangle(
|
| 289 |
+
im,
|
| 290 |
+
(int(box[0]), int(box[1])),
|
| 291 |
+
(int(box[2]), int(box[3])),
|
| 292 |
+
self.color_palette(int(cls_), bgr=True),
|
| 293 |
+
1,
|
| 294 |
+
cv2.LINE_AA,
|
| 295 |
+
)
|
| 296 |
+
cv2.putText(
|
| 297 |
+
im,
|
| 298 |
+
f"{self.classes[cls_]}: {conf:.3f}",
|
| 299 |
+
(int(box[0]), int(box[1] - 9)),
|
| 300 |
+
cv2.FONT_HERSHEY_SIMPLEX,
|
| 301 |
+
0.7,
|
| 302 |
+
self.color_palette(int(cls_), bgr=True),
|
| 303 |
+
2,
|
| 304 |
+
cv2.LINE_AA,
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
# Mix image
|
| 308 |
+
im = cv2.addWeighted(im_canvas, 0.3, im, 0.7, 0)
|
| 309 |
+
return im
|
| 310 |
+
|
| 311 |
+
def process_image(input_image,model):
|
| 312 |
+
model = YOLOv8SegONNX(model)
|
| 313 |
+
confidence_treshold = 0.25
|
| 314 |
+
nms_iou_treshold = 0.45
|
| 315 |
+
start_time = time.time()
|
| 316 |
+
img = cv2.imread(input_image)
|
| 317 |
+
boxes, segments, _ = model(img, conf_threshold=confidence_treshold, iou_threshold=nms_iou_treshold)
|
| 318 |
+
if len(boxes) > 0:
|
| 319 |
+
output_image = model.draw_and_visualize(img, boxes, segments, vis=False, save=True)
|
| 320 |
+
end_time = time.time()
|
| 321 |
+
duration = end_time - start_time
|
| 322 |
+
#TODO Refactor code to extract annotations properly
|
| 323 |
+
return f"Executed in {duration:.2f}s", input_image, output_image, boxes, segments
|
pytorch_inf.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ultralytics import YOLO
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from habitat_classification import classify_habitat, get_inconclusive
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
def get_habitat_data(class_names):
|
| 7 |
+
if not class_names:
|
| 8 |
+
inconclusive_res = get_inconclusive()
|
| 9 |
+
return inconclusive_res[0], inconclusive_res[1]
|
| 10 |
+
else:
|
| 11 |
+
habitat_res = classify_habitat(class_names)
|
| 12 |
+
return habitat_res[0], habitat_res[1]
|
| 13 |
+
|
| 14 |
+
def display_detections(frame, results):
|
| 15 |
+
detections = []
|
| 16 |
+
annotations = []
|
| 17 |
+
for result in results:
|
| 18 |
+
if result.boxes.data.nelement() != 0:
|
| 19 |
+
for detection in result.boxes.data:
|
| 20 |
+
x1, y1, x2, y2, conf, cls = detection.cpu().numpy()
|
| 21 |
+
class_name = result.names[int(cls)]
|
| 22 |
+
detections.append([class_name, conf])
|
| 23 |
+
annotations.append(((int(x1), int(y1), int(x2), int(y2)), class_name))
|
| 24 |
+
outframe = results[0].plot()
|
| 25 |
+
return frame, outframe, annotations, pd.DataFrame(detections, columns=["Class", "Confidence"])
|
| 26 |
+
|
| 27 |
+
print("No detections")
|
| 28 |
+
return frame, [], []
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def process_image(input_image, model):
|
| 32 |
+
results = model(input_image)
|
| 33 |
+
return display_detections(input_image, results)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def run_pytorch_inference(input_image, pt_model):
|
| 37 |
+
model = YOLO(pt_model)
|
| 38 |
+
model.conf = 0.2
|
| 39 |
+
start_time = time.time()
|
| 40 |
+
frame, outframe, annotations, detections = process_image(input_image, model)
|
| 41 |
+
if detections.empty:
|
| 42 |
+
habitat, probabilities = get_inconclusive()
|
| 43 |
+
detections = pd.DataFrame(columns=["Class", "Confidence"])
|
| 44 |
+
else:
|
| 45 |
+
habitat, probabilities = get_habitat_data(detections['Class'].tolist())
|
| 46 |
+
end_time = time.time()
|
| 47 |
+
duration = end_time - start_time
|
| 48 |
+
return f"Executed in {duration:.2f}s", (frame, annotations), habitat, probabilities, outframe, detections
|
requirements.txt
CHANGED
|
@@ -2,4 +2,8 @@ torch
|
|
| 2 |
pandas
|
| 3 |
ultralytics
|
| 4 |
huggingface_hub
|
| 5 |
-
python-dotenv
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
pandas
|
| 3 |
ultralytics
|
| 4 |
huggingface_hub
|
| 5 |
+
python-dotenv
|
| 6 |
+
opencv-python
|
| 7 |
+
numpy
|
| 8 |
+
onnxruntime
|
| 9 |
+
#onnxruntime-gpu
|