Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,56 +1,34 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
import numpy as np
|
| 4 |
|
| 5 |
# Load YOLOv7 model
|
| 6 |
weights_path = "cattle.pt"
|
| 7 |
config_path = "yolov7.yaml"
|
| 8 |
-
net =
|
| 9 |
-
layer_names = net.getLayerNames()
|
| 10 |
-
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
|
| 11 |
|
| 12 |
# Define function to detect objects using YOLOv7
|
| 13 |
def detect_objects(image):
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
net
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
x = int(center_x - w / 2)
|
| 35 |
-
y = int(center_y - h / 2)
|
| 36 |
-
boxes.append([x, y, w, h])
|
| 37 |
-
confidences.append(float(confidence))
|
| 38 |
-
class_ids.append(class_id)
|
| 39 |
-
|
| 40 |
-
# Non-max suppression to remove overlapping boxes
|
| 41 |
-
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
|
| 42 |
-
|
| 43 |
-
# Count detected objects
|
| 44 |
-
object_count = len(indexes)
|
| 45 |
-
|
| 46 |
-
# Draw bounding boxes on the image
|
| 47 |
-
for i in range(len(boxes)):
|
| 48 |
-
if i in indexes:
|
| 49 |
-
x, y, w, h = boxes[i]
|
| 50 |
-
label = str(class_ids[i])
|
| 51 |
-
color = (255, 0, 0) # BGR color format
|
| 52 |
-
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
|
| 53 |
-
cv2.putText(image, label, (x, y + 30), cv2.FONT_HERSHEY_PLAIN, 3, color, 3)
|
| 54 |
|
| 55 |
return image, object_count
|
| 56 |
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torchvision import transforms
|
| 3 |
import numpy as np
|
| 4 |
|
| 5 |
# Load YOLOv7 model
|
| 6 |
weights_path = "cattle.pt"
|
| 7 |
config_path = "yolov7.yaml"
|
| 8 |
+
net = None # Initialize your YOLOv7 model here
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# Define function to detect objects using YOLOv7
|
| 11 |
def detect_objects(image):
|
| 12 |
+
global net
|
| 13 |
+
|
| 14 |
+
if net is None:
|
| 15 |
+
# Initialize your YOLOv7 model if not already initialized
|
| 16 |
+
net = ...
|
| 17 |
+
|
| 18 |
+
# Perform any necessary preprocessing on the image
|
| 19 |
+
transform = transforms.Compose([
|
| 20 |
+
transforms.Resize((416, 416)), # Resize image to expected input size
|
| 21 |
+
transforms.ToTensor(), # Convert image to tensor
|
| 22 |
+
])
|
| 23 |
+
image_tensor = transform(image).unsqueeze(0)
|
| 24 |
+
|
| 25 |
+
# Perform object detection
|
| 26 |
+
with torch.no_grad():
|
| 27 |
+
# Forward pass through the network
|
| 28 |
+
outs = net(image_tensor)
|
| 29 |
+
|
| 30 |
+
# Process detection results and draw bounding boxes (similar to your previous code)
|
| 31 |
+
...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
return image, object_count
|
| 34 |
|