Update cropper.py
Browse files- cropper.py +138 -139
cropper.py
CHANGED
|
@@ -1,157 +1,156 @@
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
from functools import lru_cache
|
| 5 |
-
from typing import Literal
|
| 6 |
-
|
| 7 |
import torch
|
|
|
|
| 8 |
from PIL import Image
|
| 9 |
-
from
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
# ---------------------------------------------------------
|
| 13 |
-
# Supported modes
|
| 14 |
-
# ---------------------------------------------------------
|
| 15 |
-
Mode = Literal["eye", "vagina"]
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
|
|
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
# 1οΈβ£ CACHED YOLO LOADING (major speed boost)
|
| 23 |
-
# ---------------------------------------------------------
|
| 24 |
-
@lru_cache(maxsize=2)
|
| 25 |
-
def load_yolo_model(mode: Mode) -> YOLO:
|
| 26 |
"""
|
| 27 |
-
Load YOLO model
|
| 28 |
-
|
| 29 |
"""
|
| 30 |
-
|
| 31 |
-
model_path = MODEL_DIR / "besteyegwinf.pt"
|
| 32 |
-
else:
|
| 33 |
-
model_path = MODEL_DIR / "bestvag3.pt"
|
| 34 |
-
|
| 35 |
-
return YOLO(str(model_path))
|
| 36 |
-
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
# ---------------------------------------------------------
|
| 41 |
-
@lru_cache(maxsize=2)
|
| 42 |
-
def load_classifier_model(mode: Mode):
|
| 43 |
-
"""
|
| 44 |
-
Loads your infection scoring model ONCE.
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
#
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
"""
|
| 69 |
-
|
| 70 |
-
|
| 71 |
"""
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
)
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
x1 = max(int(x1), 0)
|
| 94 |
-
y1 = max(int(y1), 0)
|
| 95 |
-
x2 = min(int(x2), width)
|
| 96 |
-
y2 = min(int(y2), height)
|
| 97 |
-
|
| 98 |
-
# Optional margin (same as your old behavior)
|
| 99 |
-
margin = int(0.02 * max(width, height))
|
| 100 |
-
x1 = max(x1 - margin, 0)
|
| 101 |
-
y1 = max(y1 - margin, 0)
|
| 102 |
-
x2 = min(x2 + margin, width)
|
| 103 |
-
y2 = min(y2 + margin, height)
|
| 104 |
-
|
| 105 |
-
cropped = im.crop((x1, y1, x2, y2))
|
| 106 |
-
|
| 107 |
-
# Save cropped image to temp file
|
| 108 |
-
suffix = Path(image_path).suffix or ".png"
|
| 109 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 110 |
-
cropped.save(tmp.name)
|
| 111 |
-
return tmp.name
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
# ---------------------------------------------------------
|
| 115 |
-
# 4οΈβ£ INFECTION SCORE PREDICTION (your logic unchanged)
|
| 116 |
-
# ---------------------------------------------------------
|
| 117 |
-
def predict_infection_score(image_path: str, mode: Mode):
|
| 118 |
-
"""
|
| 119 |
-
Runs your original classification logic.
|
| 120 |
-
Caching only speeds up model loading β results stay identical.
|
| 121 |
-
"""
|
| 122 |
-
classifier = load_classifier_model(mode)
|
| 123 |
-
|
| 124 |
-
# If you use a custom classifier, paste your logic below.
|
| 125 |
-
# Since I donβt modify your logic, this behaves exactly as your current file.
|
| 126 |
-
|
| 127 |
-
# ------------------------
|
| 128 |
-
# Example (replace with your real code):
|
| 129 |
-
#
|
| 130 |
-
# img = Image.open(image_path).convert("RGB")
|
| 131 |
-
# tensor = transform(img).unsqueeze(0)
|
| 132 |
-
# with torch.no_grad():
|
| 133 |
-
# logits = classifier(tensor)
|
| 134 |
-
# score = logits.argmax(dim=1).item()
|
| 135 |
-
# return score
|
| 136 |
-
# ------------------------
|
| 137 |
-
|
| 138 |
-
# Otherwise, if your YOLO model predicts scores directly:
|
| 139 |
try:
|
| 140 |
-
model =
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
cls = int(results[0].probs.top1)
|
| 151 |
-
return cls
|
| 152 |
-
|
| 153 |
-
except:
|
| 154 |
-
return "N/A"
|
| 155 |
|
| 156 |
|
| 157 |
# #First deployed
|
|
|
|
| 1 |
+
from ultralytics import YOLO
|
| 2 |
+
import cv2
|
| 3 |
import os
|
| 4 |
+
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}")
|
| 38 |
+
|
| 39 |
+
model = YOLO(model_path)
|
| 40 |
+
_yolo_models[mode] = model
|
| 41 |
+
return model
|
| 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 = {}
|
| 108 |
+
|
| 109 |
+
cls_tfms = transforms.Compose([
|
| 110 |
+
transforms.Resize((224, 224)),
|
| 111 |
+
transforms.ToTensor(),
|
| 112 |
+
transforms.Normalize([0.485, 0.456, 0.406],
|
| 113 |
+
[0.229, 0.224, 0.225]),
|
| 114 |
+
])
|
| 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 |
+
|
| 123 |
+
base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 124 |
+
model_file = (
|
| 125 |
+
os.path.join(base_dir, "models/grey_and_white_eye_infection_classifier.pth")
|
| 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
|