mojad121 commited on
Commit
e73d9f4
·
verified ·
1 Parent(s): 0e04e8e

Upload 3 files

Browse files
Files changed (3) hide show
  1. dog.jpg +0 -0
  2. mujtaba_object_detection_code_export.py +132 -0
  3. plane.jpg +0 -0
dog.jpg ADDED
mujtaba_object_detection_code_export.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """mujtaba_object_detection_code_export.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1RgE9mbEiNBuPutxI86fIewscERKHyOr_
8
+ """
9
+
10
+ !pip install ultralytics datasets wandb gradio opencv-python Pillow captum torchvision --upgrade
11
+
12
+ import os
13
+ import cv2
14
+ import torch
15
+ import numpy as np
16
+ from ultralytics import YOLO
17
+ import wandb
18
+ import matplotlib.pyplot as plt
19
+ from datetime import datetime
20
+ from google.colab import userdata
21
+
22
+ wandb.login(key=userdata.get('WANDB'))
23
+
24
+ def setup_wandb():
25
+ wandb.init(project="Object-detection",
26
+ name=f"run_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
27
+ config={
28
+ "model": "yolov8n",
29
+ "dataset": "coco128",
30
+ "img_size": 640,
31
+ "batch_size": 8
32
+ })
33
+
34
+ def load_model():
35
+ model = YOLO("yolov8n.pt")
36
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
37
+ model.to(device)
38
+ return model
39
+
40
+ def train_model(model):
41
+ results = model.train(
42
+ data="coco128.yaml",
43
+ epochs=20,
44
+ imgsz=640,
45
+ batch=8,
46
+ device='0' if torch.cuda.is_available() else 'cpu',
47
+ patience=3,
48
+ save=True
49
+ )
50
+ return model
51
+
52
+ def validate_model(model):
53
+ metrics = model.val()
54
+ wandb.log({
55
+ "val/mAP50": metrics.box.map50,
56
+ "val/mAP50-95": metrics.box.map,
57
+ "val/precision": metrics.box.mp,
58
+ "val/recall": metrics.box.mr
59
+ })
60
+ return metrics
61
+
62
+ def visualize_results(results, img_path):
63
+ img = cv2.imread(img_path)
64
+ if img is None:
65
+ raise ValueError(f"Failed to load image: {img_path}")
66
+ pred_img = results[0].plot()
67
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))
68
+ ax1.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
69
+ ax1.axis('off')
70
+ ax2.imshow(cv2.cvtColor(pred_img, cv2.COLOR_BGR2RGB))
71
+ ax2.axis('off')
72
+ plt.savefig("detection_results.jpg")
73
+ plt.close()
74
+ return "detection_results.jpg"
75
+
76
+ def test_image(model, img_path="test_image.jpg"):
77
+ if not os.path.exists(img_path):
78
+ raise FileNotFoundError(f"Image not found: {img_path}")
79
+ results = model(img_path)
80
+ output_path = visualize_results(results, img_path)
81
+ wandb.log({
82
+ "test_results": wandb.Image(output_path),
83
+ "detections": results[0].boxes.cls.tolist(),
84
+ "confidences": results[0].boxes.conf.tolist()
85
+ })
86
+ return results
87
+
88
+ def webcam_demo(model):
89
+ try:
90
+ from google.colab.patches import cv2_imshow
91
+ cap = cv2.VideoCapture(0)
92
+ if not cap.isOpened():
93
+ print("Webcam not available - skipping demo")
94
+ return
95
+ print("Press 'q' to quit webcam demo")
96
+ while True:
97
+ ret, frame = cap.read()
98
+ if not ret:
99
+ break
100
+ results = model(frame)
101
+ annotated = results[0].plot()
102
+ cv2_imshow(annotated)
103
+ if cv2.waitKey(1) & 0xFF == ord('q'):
104
+ break
105
+ except Exception as e:
106
+ print(f"Webcam error: {e}")
107
+ finally:
108
+ cap.release()
109
+ cv2.destroyAllWindows()
110
+
111
+ def export_model():
112
+ trained_weights = "runs/detect/train/weights/best.pt"
113
+ model = YOLO(trained_weights)
114
+ model.export(format="torchscript")
115
+ wandb.save("best.torchscript")
116
+
117
+ def main():
118
+ setup_wandb()
119
+ model = load_model()
120
+ model = train_model(model)
121
+ validate_model(model)
122
+ test_image(model)
123
+ export_model()
124
+ wandb.finish()
125
+
126
+ if __name__ == "__main__":
127
+ main()
128
+
129
+ from google.colab import files
130
+
131
+ files.download("runs/detect/train/weights/best.torchscript")
132
+
plane.jpg ADDED