Update app.py
Browse files
app.py
CHANGED
|
@@ -57,18 +57,80 @@ def to_dutch_lower(label: str) -> str:
|
|
| 57 |
# In-memory statistieken
|
| 58 |
emotion_stats = defaultdict(int)
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
output = image.copy()
|
| 63 |
landmark_color = [(255, 0, 0), (0, 0, 255), (0, 255, 0), (255, 0, 255), (0, 255, 255)]
|
| 64 |
-
for det,
|
| 65 |
bbox = det[0:4].astype(np.int32)
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
cv.rectangle(output, (bbox[0], bbox[1]), (bbox[0]+bbox[2], bbox[1]+bbox[3]), (0, 255, 0), 2)
|
| 69 |
cv.putText(
|
| 70 |
output,
|
| 71 |
-
|
| 72 |
(bbox[0], max(0, bbox[1] - 10)),
|
| 73 |
cv.FONT_HERSHEY_SIMPLEX,
|
| 74 |
0.7,
|
|
@@ -82,16 +144,73 @@ def visualize(image, det_res, fer_res):
|
|
| 82 |
cv.circle(output, landmark, 2, landmark_color[idx], 2)
|
| 83 |
return output
|
| 84 |
|
| 85 |
-
def summarize_emotions(
|
| 86 |
-
"""Maakt de grote groene NL-lowercase samenvatting."""
|
| 87 |
-
if not
|
| 88 |
return "## **geen gezicht gedetecteerd**"
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
return f"# **{top}**\n\n_Gedetecteerde emoties: {details}_"
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
# --- Staafdiagram tekenen met OpenCV (geen matplotlib nodig) ---
|
| 96 |
def draw_bar_chart_cv(stats: dict, width=640, height=320):
|
| 97 |
img = np.full((height, width, 3), 255, dtype=np.uint8)
|
|
@@ -133,36 +252,6 @@ def draw_bar_chart_cv(stats: dict, width=640, height=320):
|
|
| 133 |
|
| 134 |
return cv.cvtColor(img, cv.COLOR_BGR2RGB)
|
| 135 |
|
| 136 |
-
def process_image(input_image):
|
| 137 |
-
"""Helper: run detectie en retourneer (output_img, fer_res as list[int])."""
|
| 138 |
-
image = cv.cvtColor(input_image, cv.COLOR_RGB2BGR)
|
| 139 |
-
h, w, _ = image.shape
|
| 140 |
-
detect_model.setInputSize([w, h])
|
| 141 |
-
dets = detect_model.infer(image)
|
| 142 |
-
if dets is None:
|
| 143 |
-
return cv.cvtColor(image, cv.COLOR_BGR2RGB), []
|
| 144 |
-
fer_res = [fer_model.infer(image, face_points[:-1])[0] for face_points in dets]
|
| 145 |
-
output = visualize(image, dets, fer_res)
|
| 146 |
-
return cv.cvtColor(output, cv.COLOR_BGR2RGB), fer_res
|
| 147 |
-
|
| 148 |
-
def detect_expression(input_image):
|
| 149 |
-
"""Versie die WÉL statistieken bijwerkt (gebruik voor 'Verstuur')."""
|
| 150 |
-
output_img, fer_res = process_image(input_image)
|
| 151 |
-
emotion_md = summarize_emotions(fer_res)
|
| 152 |
-
# update stats in NL-lowercase
|
| 153 |
-
names_nl = [to_dutch_lower(FacialExpressionRecog.getDesc(x)) for x in fer_res]
|
| 154 |
-
for name in names_nl:
|
| 155 |
-
emotion_stats[name] += 1
|
| 156 |
-
stats_plot = draw_bar_chart_cv(emotion_stats)
|
| 157 |
-
return output_img, emotion_md, stats_plot
|
| 158 |
-
|
| 159 |
-
def detect_expression_no_stats(input_image):
|
| 160 |
-
"""Versie die GEEN statistieken bijwerkt (gebruik voor gr.Examples & caching)."""
|
| 161 |
-
output_img, fer_res = process_image(input_image)
|
| 162 |
-
emotion_md = summarize_emotions(fer_res)
|
| 163 |
-
# géén stats update en ook géén stats_image teruggeven
|
| 164 |
-
return output_img, emotion_md
|
| 165 |
-
|
| 166 |
# Voorbeelden automatisch laden
|
| 167 |
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
|
| 168 |
EXAMPLES_DIR = Path("examples")
|
|
|
|
| 57 |
# In-memory statistieken
|
| 58 |
emotion_stats = defaultdict(int)
|
| 59 |
|
| 60 |
+
# ---------- Confidence helpers ----------
|
| 61 |
+
def _format_pct(conf):
|
| 62 |
+
"""Format confidence naar '82%' (int). Conf kan in [0,1] of [0,100] of None."""
|
| 63 |
+
if conf is None:
|
| 64 |
+
return None
|
| 65 |
+
try:
|
| 66 |
+
c = float(conf)
|
| 67 |
+
except Exception:
|
| 68 |
+
return None
|
| 69 |
+
if c <= 1.0:
|
| 70 |
+
c *= 100.0
|
| 71 |
+
c = max(0.0, min(100.0, c))
|
| 72 |
+
return f"{int(round(c))}%"
|
| 73 |
+
|
| 74 |
+
def _parse_infer_output(result):
|
| 75 |
+
"""
|
| 76 |
+
Probeer robuust (label_idx, confidence) uit infer-output te halen.
|
| 77 |
+
Ondersteunt:
|
| 78 |
+
- (label, score) tuple/list
|
| 79 |
+
- [probs...] ndarray (neemt argmax + max)
|
| 80 |
+
- [label] of scalar -> (label, None)
|
| 81 |
+
"""
|
| 82 |
+
# numpy array?
|
| 83 |
+
if isinstance(result, np.ndarray):
|
| 84 |
+
arr = result
|
| 85 |
+
if arr.ndim == 1 and arr.size > 1:
|
| 86 |
+
idx = int(np.argmax(arr))
|
| 87 |
+
conf = float(arr[idx])
|
| 88 |
+
return idx, conf
|
| 89 |
+
elif arr.size == 1:
|
| 90 |
+
return int(arr.flat[0]), None
|
| 91 |
+
else:
|
| 92 |
+
# onbekende vorm
|
| 93 |
+
try:
|
| 94 |
+
idx = int(arr[0])
|
| 95 |
+
return idx, None
|
| 96 |
+
except Exception:
|
| 97 |
+
return 0, None
|
| 98 |
+
|
| 99 |
+
# list/tuple?
|
| 100 |
+
if isinstance(result, (list, tuple)):
|
| 101 |
+
if len(result) >= 2 and isinstance(result[1], (float, np.floating, int, np.integer)):
|
| 102 |
+
try:
|
| 103 |
+
return int(result[0]), float(result[1])
|
| 104 |
+
except Exception:
|
| 105 |
+
pass
|
| 106 |
+
if len(result) >= 1:
|
| 107 |
+
try:
|
| 108 |
+
return int(result[0]), None
|
| 109 |
+
except Exception:
|
| 110 |
+
return 0, None
|
| 111 |
+
|
| 112 |
+
# scalar label
|
| 113 |
+
try:
|
| 114 |
+
return int(result), None
|
| 115 |
+
except Exception:
|
| 116 |
+
return 0, None
|
| 117 |
+
# ---------------------------------------
|
| 118 |
+
|
| 119 |
+
def visualize(image, det_res, labels, confs):
|
| 120 |
+
"""Tekent bbox + NL-lowercase emotielabel + confidence op de output."""
|
| 121 |
output = image.copy()
|
| 122 |
landmark_color = [(255, 0, 0), (0, 0, 255), (0, 255, 0), (255, 0, 255), (0, 255, 255)]
|
| 123 |
+
for i, (det, lab) in enumerate(zip(det_res, labels)):
|
| 124 |
bbox = det[0:4].astype(np.int32)
|
| 125 |
+
label_en = FacialExpressionRecog.getDesc(lab)
|
| 126 |
+
fer_type_str_nl = to_dutch_lower(label_en)
|
| 127 |
+
pct = _format_pct(confs[i] if i < len(confs) else None)
|
| 128 |
+
txt = f"{fer_type_str_nl}" + (f" {pct}" if pct else "")
|
| 129 |
|
| 130 |
cv.rectangle(output, (bbox[0], bbox[1]), (bbox[0]+bbox[2], bbox[1]+bbox[3]), (0, 255, 0), 2)
|
| 131 |
cv.putText(
|
| 132 |
output,
|
| 133 |
+
txt,
|
| 134 |
(bbox[0], max(0, bbox[1] - 10)),
|
| 135 |
cv.FONT_HERSHEY_SIMPLEX,
|
| 136 |
0.7,
|
|
|
|
| 144 |
cv.circle(output, landmark, 2, landmark_color[idx], 2)
|
| 145 |
return output
|
| 146 |
|
| 147 |
+
def summarize_emotions(labels, confs):
|
| 148 |
+
"""Maakt de grote groene NL-lowercase samenvatting met gemiddelden per emotie."""
|
| 149 |
+
if not labels:
|
| 150 |
return "## **geen gezicht gedetecteerd**"
|
| 151 |
+
|
| 152 |
+
names_nl = []
|
| 153 |
+
for lab in labels:
|
| 154 |
+
names_nl.append(to_dutch_lower(FacialExpressionRecog.getDesc(lab)))
|
| 155 |
+
|
| 156 |
+
# tel per emotie + verzamel confidences
|
| 157 |
+
counts = Counter(names_nl)
|
| 158 |
+
conf_bucket = defaultdict(list)
|
| 159 |
+
for i, name in enumerate(names_nl):
|
| 160 |
+
if i < len(confs) and confs[i] is not None:
|
| 161 |
+
conf_bucket[name].append(float(confs[i]))
|
| 162 |
+
|
| 163 |
+
# top-emotie op basis van count
|
| 164 |
+
top = counts.most_common(1)[0][0]
|
| 165 |
+
|
| 166 |
+
# details: "blij (2, gem. 79%)"
|
| 167 |
+
parts = []
|
| 168 |
+
# sorteer op frequentie aflopend, dan alfabetisch
|
| 169 |
+
for name, n in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
|
| 170 |
+
if conf_bucket[name]:
|
| 171 |
+
avg = sum(conf_bucket[name]) / len(conf_bucket[name])
|
| 172 |
+
parts.append(f"{name} ({n}, gem. {_format_pct(avg)})")
|
| 173 |
+
else:
|
| 174 |
+
parts.append(f"{name} ({n})")
|
| 175 |
+
details = ", ".join(parts)
|
| 176 |
+
|
| 177 |
return f"# **{top}**\n\n_Gedetecteerde emoties: {details}_"
|
| 178 |
|
| 179 |
+
def process_image(input_image):
|
| 180 |
+
"""Helper: run detectie en retourneer (output_img, labels[int], confs[float|None])."""
|
| 181 |
+
image = cv.cvtColor(input_image, cv.COLOR_RGB2BGR)
|
| 182 |
+
h, w, _ = image.shape
|
| 183 |
+
detect_model.setInputSize([w, h])
|
| 184 |
+
dets = detect_model.infer(image)
|
| 185 |
+
if dets is None:
|
| 186 |
+
return cv.cvtColor(image, cv.COLOR_BGR2RGB), [], [], None
|
| 187 |
+
labels, confs = [], []
|
| 188 |
+
for face_points in dets:
|
| 189 |
+
raw = fer_model.infer(image, face_points[:-1])
|
| 190 |
+
lab, conf = _parse_infer_output(raw)
|
| 191 |
+
labels.append(lab)
|
| 192 |
+
confs.append(conf)
|
| 193 |
+
output = visualize(image, dets, labels, confs)
|
| 194 |
+
return cv.cvtColor(output, cv.COLOR_BGR2RGB), labels, confs, dets
|
| 195 |
+
|
| 196 |
+
def detect_expression(input_image):
|
| 197 |
+
"""Versie die WÉL statistieken bijwerkt (gebruik voor 'Verstuur')."""
|
| 198 |
+
output_img, labels, confs, _ = process_image(input_image)
|
| 199 |
+
emotion_md = summarize_emotions(labels, confs)
|
| 200 |
+
# update stats in NL-lowercase
|
| 201 |
+
for lab in labels:
|
| 202 |
+
name_nl = to_dutch_lower(FacialExpressionRecog.getDesc(lab))
|
| 203 |
+
emotion_stats[name_nl] += 1
|
| 204 |
+
stats_plot = draw_bar_chart_cv(emotion_stats)
|
| 205 |
+
return output_img, emotion_md, stats_plot
|
| 206 |
+
|
| 207 |
+
def detect_expression_no_stats(input_image):
|
| 208 |
+
"""Versie die GEEN statistieken bijwerkt (gebruik voor gr.Examples & caching)."""
|
| 209 |
+
output_img, labels, confs, _ = process_image(input_image)
|
| 210 |
+
emotion_md = summarize_emotions(labels, confs)
|
| 211 |
+
# géén stats update en ook géén stats_image teruggeven
|
| 212 |
+
return output_img, emotion_md
|
| 213 |
+
|
| 214 |
# --- Staafdiagram tekenen met OpenCV (geen matplotlib nodig) ---
|
| 215 |
def draw_bar_chart_cv(stats: dict, width=640, height=320):
|
| 216 |
img = np.full((height, width, 3), 255, dtype=np.uint8)
|
|
|
|
| 252 |
|
| 253 |
return cv.cvtColor(img, cv.COLOR_BGR2RGB)
|
| 254 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
# Voorbeelden automatisch laden
|
| 256 |
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
|
| 257 |
EXAMPLES_DIR = Path("examples")
|