Noursine commited on
Commit
6501992
·
verified ·
1 Parent(s): 9e17458

Update yolo_Anomaly

Browse files
Files changed (1) hide show
  1. yolo_Anomaly +64 -0
yolo_Anomaly CHANGED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from ultralytics import YOLO
4
+ from PIL import Image
5
+
6
+ # Load YOLO model
7
+ def load_model(model_path="best.pt"):
8
+ """Load the YOLO model"""
9
+ model = YOLO(model_path)
10
+ return model
11
+
12
+ # Process image
13
+ def process_image(image, model):
14
+ """Run YOLO prediction on the given image"""
15
+ if isinstance(image, Image.Image):
16
+ image_array = np.array(image)
17
+ else:
18
+ image_array = image
19
+
20
+ results = model.predict(image_array)
21
+ return results[0] # return first result
22
+
23
+ # Draw all predictions
24
+ def draw_predictions(image, results):
25
+ """Draw bounding boxes and labels"""
26
+ if isinstance(image, Image.Image):
27
+ image_array = np.array(image)
28
+ else:
29
+ image_array = image
30
+
31
+ plotted_image = results.plot() # YOLO's built-in plotting
32
+ return Image.fromarray(plotted_image)
33
+
34
+ # Group predictions by class/condition
35
+ def group_predictions_by_condition(results):
36
+ """Organize detections by class"""
37
+ condition_groups = {}
38
+ if len(results.boxes) > 0:
39
+ for box in results.boxes:
40
+ class_id = int(box.cls[0])
41
+ class_name = results.names[class_id]
42
+ confidence = float(box.conf[0])
43
+ if class_name not in condition_groups:
44
+ condition_groups[class_name] = []
45
+ condition_groups[class_name].append({
46
+ 'box': box,
47
+ 'confidence': confidence
48
+ })
49
+ return condition_groups
50
+
51
+ # Example usage (standalone)
52
+ if __name__ == "__main__":
53
+ model = load_model("best.pt")
54
+ img_path = "your_test_image.jpg"
55
+ image = Image.open(img_path)
56
+
57
+ results = process_image(image, model)
58
+ grouped = group_predictions_by_condition(results)
59
+
60
+ print("Grouped Predictions:", grouped)
61
+
62
+ # Save output visualization
63
+ output_img = draw_predictions(image, results)
64
+ output_img.save("predicted_output.jpg")