Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,30 +8,34 @@ import onnxruntime
|
|
| 8 |
from pathlib import Path
|
| 9 |
from ultralytics import YOLO
|
| 10 |
|
| 11 |
-
# Load YOLOv5 model
|
| 12 |
-
model =
|
| 13 |
-
|
| 14 |
-
# Export to ONNX format
|
| 15 |
-
model.export(format="onnx", dynamic=True)
|
| 16 |
-
|
| 17 |
-
os.makedirs("models", exist_ok=True)
|
| 18 |
|
|
|
|
| 19 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
-
|
|
|
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
model.eval()
|
| 28 |
-
|
| 29 |
-
# Exporting to ONNX
|
| 30 |
-
model.export(format="onnx", dynamic=True)
|
| 31 |
-
os.rename("yolov5n.onnx", model_path)
|
| 32 |
-
del model # Free memory
|
| 33 |
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
session = onnxruntime.InferenceSession(str(model_path), providers=['CUDAExecutionProvider'])
|
| 36 |
|
| 37 |
# Generate random colors for each class
|
|
@@ -50,7 +54,7 @@ def detect_objects(image):
|
|
| 50 |
|
| 51 |
# Preprocess image
|
| 52 |
original_shape = image.shape
|
| 53 |
-
input_shape = (
|
| 54 |
image_resized = cv2.resize(image, input_shape)
|
| 55 |
image_norm = image_resized.astype(np.float32) / 255.0
|
| 56 |
image_transposed = np.transpose(image_norm, (2, 0, 1))
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
from ultralytics import YOLO
|
| 10 |
|
| 11 |
+
# Load YOLOv5 model without AutoShape
|
| 12 |
+
model = torch.hub.load("ultralytics/yolov5", "yolov5n", source="local")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Set device
|
| 15 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 16 |
+
model.to(device)
|
| 17 |
+
model.eval()
|
| 18 |
|
| 19 |
+
# Fuse layers for optimization
|
| 20 |
+
model.fuse()
|
| 21 |
|
| 22 |
+
# Export to ONNX format
|
| 23 |
+
os.makedirs("models", exist_ok=True)
|
| 24 |
+
model_path = Path("models/yolov5n.onnx")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
torch.onnx.export(
|
| 27 |
+
model,
|
| 28 |
+
torch.zeros(1, 3, 640, 640).to(device), # Input tensor
|
| 29 |
+
str(model_path),
|
| 30 |
+
export_params=True,
|
| 31 |
+
opset_version=11,
|
| 32 |
+
do_constant_folding=True,
|
| 33 |
+
input_names=["images"],
|
| 34 |
+
output_names=["output"],
|
| 35 |
+
dynamic_axes={"images": {0: "batch_size"}, "output": {0: "batch_size"}}
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Load ONNX model for inference
|
| 39 |
session = onnxruntime.InferenceSession(str(model_path), providers=['CUDAExecutionProvider'])
|
| 40 |
|
| 41 |
# Generate random colors for each class
|
|
|
|
| 54 |
|
| 55 |
# Preprocess image
|
| 56 |
original_shape = image.shape
|
| 57 |
+
input_shape = (640, 640)
|
| 58 |
image_resized = cv2.resize(image, input_shape)
|
| 59 |
image_norm = image_resized.astype(np.float32) / 255.0
|
| 60 |
image_transposed = np.transpose(image_norm, (2, 0, 1))
|