Pradnya99 commited on
Commit
3d7c423
Β·
verified Β·
1 Parent(s): c38587a

Update cropper.py

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