Pradnya99 commited on
Commit
86d99b3
Β·
verified Β·
1 Parent(s): 096ba00

Update cropper.py

Browse files
Files changed (1) hide show
  1. cropper.py +31 -45
cropper.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from ultralytics import YOLO
2
  import cv2
3
  import os
@@ -5,99 +6,85 @@ import numpy as np
5
  import torch
6
  from torchvision import models, transforms
7
  from PIL import Image
 
 
8
 
9
  # ─────────────────────────────
10
- # 1️⃣ YOLO Model Loader (with caching)
11
  # ─────────────────────────────
12
- _yolo_models = {}
13
-
14
  def load_model(mode="eye"):
15
- global _yolo_models
16
-
17
- if mode in _yolo_models:
18
- return _yolo_models[mode]
19
-
20
  base_dir = os.path.dirname(os.path.abspath(__file__))
21
-
22
  if mode == "eye":
23
  model_path = os.path.join(base_dir, "models/besteyegwinf.pt")
24
- else:
25
  model_path = os.path.join(base_dir, "models/bestvag3.pt")
26
-
 
27
  if not os.path.exists(model_path):
28
  raise FileNotFoundError(f"Model not found: {model_path}")
29
-
30
- model = YOLO(model_path)
31
- _yolo_models[mode] = model
32
- return model
33
 
34
 
35
  # ─────────────────────────────
36
- # 2️⃣ Pad crops to fixed rectangle
37
  # ─────────────────────────────
38
  def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
 
39
  h, w = image.shape[:2]
40
  scale = min(target_w / w, target_h / h)
41
  new_w, new_h = int(w * scale), int(h * scale)
42
-
43
  resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
44
-
45
  canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
46
-
47
  x_offset = (target_w - new_w) // 2
48
  y_offset = (target_h - new_h) // 2
49
-
50
  canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
51
  return canvas
52
 
53
 
54
  # ─────────────────────────────
55
- # 3️⃣ YOLO crop (your original logic)
56
  # ─────────────────────────────
57
  def crop_with_yolo(img_path, mode="eye"):
58
  try:
59
- model = load_model(mode)
60
  conf_value = 0.55 if mode == "eye" else 0.05
61
-
62
- results = model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
63
 
64
  img = cv2.imread(img_path)
65
  if img is None:
66
- print(f"[ERROR] Cannot read image: {img_path}")
67
  return img_path
68
 
69
  if not results or not len(results[0].boxes):
70
- print(f"[WARN] No detection for {img_path}")
71
  padded = pad_to_fixed_rectangle(img)
72
  out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
73
  cv2.imwrite(out_path, padded)
74
  return out_path
75
 
76
- box = results[0].boxes[results[0].boxes.conf.argmax()]
77
- x1, y1, x2, y2 = map(int, box.xyxy[0])
78
-
79
  h, w = img.shape[:2]
80
- x1, y1 = max(0, x1), max(0, y1)
81
- x2, y2 = min(w, x2), min(h, y2)
82
 
83
  crop = img[y1:y2, x1:x2].copy()
84
-
85
- padded = pad_to_fixed_rectangle(crop, 1000, 700)
86
  out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
87
  cv2.imwrite(out_path, padded)
 
88
  return out_path
89
 
90
  except Exception as e:
91
- print(f"[ERROR] YOLO crop error: {e}")
92
  return img_path
93
 
94
 
95
  # ─────────────────────────────
96
- # 4️⃣ EfficientNet classifier (unchanged)
97
  # ─────────────────────────────
98
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
99
  _loaded_classifiers = {}
100
-
101
  cls_tfms = transforms.Compose([
102
  transforms.Resize((224, 224)),
103
  transforms.ToTensor(),
@@ -105,10 +92,9 @@ cls_tfms = transforms.Compose([
105
  [0.229, 0.224, 0.225]),
106
  ])
107
 
108
-
109
  def load_classifier(mode="eye"):
 
110
  global _loaded_classifiers
111
-
112
  if mode in _loaded_classifiers:
113
  return _loaded_classifiers[mode]
114
 
@@ -118,30 +104,30 @@ def load_classifier(mode="eye"):
118
  if mode == "eye"
119
  else os.path.join(base_dir, "models/vagina_infection_classifier.pth")
120
  )
121
-
122
  if not os.path.exists(model_file):
123
- raise FileNotFoundError(f"Classifier not found: {model_file}")
124
 
125
  model = models.efficientnet_b0(weights=None)
126
  model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5)
127
-
128
  model.load_state_dict(torch.load(model_file, map_location=device))
129
  model.eval().to(device)
130
-
131
  _loaded_classifiers[mode] = model
 
132
  return model
133
 
134
 
135
- def predict_infection_score(image_path, mode="eye"):
 
136
  try:
137
  model = load_classifier(mode)
138
  img = Image.open(image_path).convert("RGB")
139
  x = cls_tfms(img).unsqueeze(0).to(device)
140
  with torch.no_grad():
141
  logits = model(x)
142
- return logits.argmax(1).item() + 1
 
143
  except Exception as e:
144
- print(f"[ERROR] Score prediction error: {e}")
145
  return None
146
 
147
  # #First deployed
 
1
+
2
  from ultralytics import YOLO
3
  import cv2
4
  import os
 
6
  import torch
7
  from torchvision import models, transforms
8
  from PIL import Image
9
+ from pptx import Presentation
10
+ from pptx.util import Inches, Emu, Pt
11
 
12
  # ─────────────────────────────
13
+ # 1️⃣ YOLO Model Loader
14
  # ─────────────────────────────
 
 
15
  def load_model(mode="eye"):
 
 
 
 
 
16
  base_dir = os.path.dirname(os.path.abspath(__file__))
 
17
  if mode == "eye":
18
  model_path = os.path.join(base_dir, "models/besteyegwinf.pt")
19
+ elif mode == "vagina":
20
  model_path = os.path.join(base_dir, "models/bestvag3.pt")
21
+ else:
22
+ raise ValueError("Invalid mode! Use 'eye' or 'vagina'.")
23
  if not os.path.exists(model_path):
24
  raise FileNotFoundError(f"Model not found: {model_path}")
25
+ return YOLO(model_path)
 
 
 
26
 
27
 
28
  # ─────────────────────────────
29
+ # 2️⃣ Pad All Crops to Same Rectangular Size (no distortion)
30
  # ─────────────────────────────
31
  def pad_to_fixed_rectangle(image, target_w=1000, target_h=700):
32
+ """Fits cropped image into fixed rectangle without stretching."""
33
  h, w = image.shape[:2]
34
  scale = min(target_w / w, target_h / h)
35
  new_w, new_h = int(w * scale), int(h * scale)
 
36
  resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
 
37
  canvas = np.ones((target_h, target_w, 3), dtype=np.uint8) * 255
 
38
  x_offset = (target_w - new_w) // 2
39
  y_offset = (target_h - new_h) // 2
 
40
  canvas[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized
41
  return canvas
42
 
43
 
44
  # ─────────────────────────────
45
+ # 3️⃣ Crop Image with YOLO
46
  # ─────────────────────────────
47
  def crop_with_yolo(img_path, mode="eye"):
48
  try:
49
+ yolo_model = load_model(mode)
50
  conf_value = 0.55 if mode == "eye" else 0.05
51
+ results = yolo_model.predict(img_path, conf=conf_value, iou=0.6, verbose=False)
 
52
 
53
  img = cv2.imread(img_path)
54
  if img is None:
55
+ print(f"[ERROR] Could not read {img_path}")
56
  return img_path
57
 
58
  if not results or not len(results[0].boxes):
59
+ print(f"[WARN] No detection for {img_path} ({mode})")
60
  padded = pad_to_fixed_rectangle(img)
61
  out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
62
  cv2.imwrite(out_path, padded)
63
  return out_path
64
 
65
+ boxes = results[0].boxes
66
+ best = boxes[boxes.conf.argmax()]
67
+ x1, y1, x2, y2 = map(int, best.xyxy[0])
68
  h, w = img.shape[:2]
69
+ x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
 
70
 
71
  crop = img[y1:y2, x1:x2].copy()
72
+ padded = pad_to_fixed_rectangle(crop, target_w=1000, target_h=700)
 
73
  out_path = os.path.splitext(img_path)[0] + f"_{mode}_cropped.jpg"
74
  cv2.imwrite(out_path, padded)
75
+ print(f"[INFO] Saved {out_path}")
76
  return out_path
77
 
78
  except Exception as e:
79
+ print(f"[ERROR] YOLO cropping failed: {e}")
80
  return img_path
81
 
82
 
83
  # ─────────────────────────────
84
+ # 4️⃣ Infection Score Classifier (EfficientNet for eye & vagina)
85
  # ─────────────────────────────
86
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
87
  _loaded_classifiers = {}
 
88
  cls_tfms = transforms.Compose([
89
  transforms.Resize((224, 224)),
90
  transforms.ToTensor(),
 
92
  [0.229, 0.224, 0.225]),
93
  ])
94
 
 
95
  def load_classifier(mode="eye"):
96
+ """Loads the correct classifier (eye/vagina) only once."""
97
  global _loaded_classifiers
 
98
  if mode in _loaded_classifiers:
99
  return _loaded_classifiers[mode]
100
 
 
104
  if mode == "eye"
105
  else os.path.join(base_dir, "models/vagina_infection_classifier.pth")
106
  )
 
107
  if not os.path.exists(model_file):
108
+ raise FileNotFoundError(f"Classifier model not found: {model_file}")
109
 
110
  model = models.efficientnet_b0(weights=None)
111
  model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, 5)
 
112
  model.load_state_dict(torch.load(model_file, map_location=device))
113
  model.eval().to(device)
 
114
  _loaded_classifiers[mode] = model
115
+ print(f"[INFO] Loaded classifier for {mode}")
116
  return model
117
 
118
 
119
+ def predict_infection_score(image_path: str, mode="eye") -> int:
120
+ """Predicts infection score (1–5) for both eyes and vaginas."""
121
  try:
122
  model = load_classifier(mode)
123
  img = Image.open(image_path).convert("RGB")
124
  x = cls_tfms(img).unsqueeze(0).to(device)
125
  with torch.no_grad():
126
  logits = model(x)
127
+ pred = logits.argmax(1).item() + 1
128
+ return pred
129
  except Exception as e:
130
+ print(f"[ERROR] Score prediction failed: {e}")
131
  return None
132
 
133
  # #First deployed