File size: 34,415 Bytes
b0acf7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5642696a",
   "metadata": {},
   "source": [
    "# Image Preprocessing Lab\n",
    "\n",
    "Everything the demo does lives in this notebook: every preprocessing step, the two preset lines, and the two models.\n",
    "It is plain Python: functions and dictionaries, no classes.\n",
    "\n",
    "The lab tells two stories about the same idea, **a model only works on the input it was trained on**:\n",
    "\n",
    "1. **Classify** a pet photo with ResNet50.\n",
    "2. **Segment and count** objects with YOLO11s-seg.\n",
    "\n",
    "Each line has three kinds of steps:\n",
    "\n",
    "- **Preparation** steps turn a photo into exactly what the model expects. They are on.\n",
    "- **Break it** steps copy what the real world does to photos: tilted cameras, dark rooms, blur, sensor noise,\n",
    "  low resolution. They are off. Switch one on and watch the model's answer change.\n",
    "- **Fix it** steps are classic enhancement and restoration: straighten, brighten, equalize, denoise, sharpen.\n",
    "  They are off too. Break the photo, switch on a fix, and see how much of the answer comes back (often only part).\n",
    "\n",
    "**The web app loads this same notebook.** `server.py` runs every cell *except* the ones tagged `demo` (at the end),\n",
    "so a function you change here changes what the app runs and shows.\n",
    "\n",
    "Conventions: images are NumPy arrays. Color images are `(height, width, 3)` in **RGB** order and `uint8` (0..255),\n",
    "except straight after `cv2.imread`, which gives **BGR**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d2c5fe2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "# Every step the app can use: step id -> dict(name, kind, fn, params, summary, explain).\n",
    "STEPS = {}\n",
    "\n",
    "KINDS = {\n",
    "    \"prep\": \"Preparation\",  # what the model needs\n",
    "    \"break\": \"Break it\",    # what the real world does to photos\n",
    "    \"fix\": \"Fix it\",        # enhancement and restoration that try to undo the damage\n",
    "}\n",
    "\n",
    "\n",
    "def slider(name, default, lo, hi, step=1, label=None, odd=False):\n",
    "    is_int = all(isinstance(v, int) for v in (default, lo, hi, step))\n",
    "    return dict(name=name, type=\"int\" if is_int else \"float\", default=default,\n",
    "                min=lo, max=hi, step=step, label=label or name, odd=odd)\n",
    "\n",
    "\n",
    "def add_step(fn, name, kind, summary, explain, params=(), short=None, helps=()):\n",
    "    # short: a label that fits on a step pill (defaults to name).\n",
    "    # helps: for a fix step, the break-it steps it counteracts.\n",
    "    STEPS[fn.__name__] = dict(id=fn.__name__, name=name, short=short or name, kind=kind, fn=fn,\n",
    "                              params=list(params), summary=summary, explain=explain, helps=list(helps))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c869e68",
   "metadata": {},
   "source": [
    "## Load an image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c24212e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_image(path, max_side=640):\n",
    "    img = cv2.imread(str(path))  # OpenCV loads 3 channels in B, G, R order, dtype uint8\n",
    "    h, w = img.shape[:2]\n",
    "    s = max_side / max(h, w)\n",
    "    if s < 1:  # keep the demo fast: shrink big photos, never enlarge small ones\n",
    "        img = cv2.resize(img, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)\n",
    "    return img"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bae4c60e",
   "metadata": {},
   "source": [
    "## Preparation: what the model needs\n",
    "\n",
    "A trained network expects one exact kind of input: a fixed color order, a fixed size, a fixed value range and a\n",
    "fixed memory layout. These steps get a photo there."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77fd08a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def bgr_to_rgb(img):\n",
    "    return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
    "\n",
    "add_step(bgr_to_rgb, \"BGR to RGB\", \"prep\", short=\"BGR → RGB\",\n",
    "    summary=\"Swap OpenCV's blue-first channel order to red-first.\",\n",

    "    explain=\"cv2.imread returns pixels as Blue, Green, Red. The models were trained on Red, Green, Blue. \"\n",

    "            \"Switch this off and every red turns blue: the model still answers, just less sure, \"\n",

    "            \"and nothing crashes. A classic silent bug.\")"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "d0313d1b",

   "metadata": {},

   "outputs": [],

   "source": [

    "def resize_shorter(img, size=256):\n",

    "    h, w = img.shape[:2]\n",

    "    s = size / min(h, w)\n",

    "    return cv2.resize(img, (round(w * s), round(h * s)), interpolation=cv2.INTER_AREA)\n",

    "\n",

    "add_step(resize_shorter, \"Resize\", \"prep\",\n",

    "    summary=\"Scale the shorter side to 256 pixels, keeping the shape.\",\n",

    "    explain=\"ResNet50 was trained on 224 by 224 images. First the shorter side is scaled to 256 so nothing gets \"\n",

    "            \"squashed, then the next step cuts out the middle.\",\n",

    "    params=[slider(\"size\", 256, 128, 512, 8)])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "dba55c8a",

   "metadata": {},

   "outputs": [],

   "source": [

    "def center_crop(img, size=224):\n",

    "    h, w = img.shape[:2]\n",

    "    top, left = max(0, (h - size) // 2), max(0, (w - size) // 2)\n",

    "    return img[top:top + size, left:left + size]\n",

    "\n",

    "add_step(center_crop, \"Center crop\", \"prep\", short=\"Crop\",\n",

    "    summary=\"Cut a 224 by 224 square from the middle.\",\n",

    "    explain=\"Cropping is plain array slicing: rows first, then columns. Anything near the border is thrown \"\n",

    "            \"away, so an animal that is off to the side can be cut out here.\",\n",

    "    params=[slider(\"size\", 224, 64, 512, 8)])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "e070fbbc",

   "metadata": {},

   "outputs": [],

   "source": [

    "def letterbox(img, size=640):\n",

    "    h, w = img.shape[:2]\n",

    "    s = size / max(h, w)\n",

    "    nh, nw = round(h * s), round(w * s)\n",

    "    resized = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)\n",

    "    top, left = (size - nh) // 2, (size - nw) // 2\n",

    "    return cv2.copyMakeBorder(resized, top, size - nh - top, left, size - nw - left,\n",

    "                              cv2.BORDER_CONSTANT, value=(114, 114, 114))\n",

    "\n",

    "add_step(letterbox, \"Letterbox\", \"prep\",\n",

    "    summary=\"Fit the photo into a 640 by 640 square, padding with grey.\",\n",

    "    explain=\"YOLO takes a square image but must not stretch objects. Letterboxing scales the long side to 640, \"\n",

    "            \"then fills the rest with grey (114). Stretching instead would turn round objects into ovals.\",\n",

    "    params=[slider(\"size\", 640, 320, 1024, 32)])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "aa24a1f5",

   "metadata": {},

   "outputs": [],

   "source": [

    "def normalize(img):\n",

    "    mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)\n",

    "    std = np.array([0.229, 0.224, 0.225], dtype=np.float32)\n",

    "    return (img.astype(np.float32) / 255.0 - mean) / std\n",

    "\n",

    "add_step(normalize, \"Normalize\", \"prep\",\n",

    "    summary=\"Turn 0..255 pixel values into small numbers around 0.\",\n",

    "    explain=\"Divide by 255 to get 0..1, then subtract the ImageNet mean and divide by its standard deviation, \"\n",

    "            \"per channel. The model was trained on values roughly between -2 and 2. Switch this off and it \"\n",

    "            \"receives values up to 255: its answer becomes nonsense.\")"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "6ec55aa2",

   "metadata": {},

   "outputs": [],

   "source": [

    "def to_chw(img):\n",

    "    return np.ascontiguousarray(img.transpose(2, 0, 1))\n",

    "\n",

    "add_step(to_chw, \"Channels first\", \"prep\", short=\"HWC → CHW\",\n",

    "    summary=\"Reorder the array from height, width, channels to channels, height, width.\",\n",

    "    explain=\"Images are stored as (224, 224, 3). PyTorch wants (3, 224, 224). No pixel changes, only the order \"\n",

    "            \"of the axes in memory.\")"

   ]

  },

  {

   "cell_type": "markdown",

   "id": "51221b67",

   "metadata": {},

   "source": [

    "## Break it: what the real world does to photos\n",

    "\n",

    "Each of these copies a problem real photos have. They are switched off in the presets."

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "c1aa6046",

   "metadata": {},

   "outputs": [],

   "source": [

    "def rotate(img, angle=45):\n",

    "    h, w = img.shape[:2]\n",

    "    M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)\n",

    "    return cv2.warpAffine(img, M, (w, h))\n",

    "\n",

    "add_step(rotate, \"Rotate\", \"break\",\n",

    "    summary=\"Tilt the photo, like a phone held at an angle.\",\n",

    "    explain=\"Most training photos are upright, so the model has rarely seen a tilted dog. The corners that \"\n",

    "            \"rotate out of frame are filled with black, which the model can mistake for content.\",\n",

    "    params=[slider(\"angle\", 45, -180, 180, 5, \"angle (degrees)\")])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "82791573",

   "metadata": {},

   "outputs": [],

   "source": [

    "def darken(img, contrast=0.05, brightness=0):\n",

    "    return cv2.convertScaleAbs(img, alpha=contrast, beta=brightness)\n",

    "\n",

    "add_step(darken, \"Dark photo\", \"break\", short=\"Dark\",\n",

    "    summary=\"Make the photo dim and flat, like a shot in a dark room.\",\n",

    "    explain=\"Every pixel is multiplied by the contrast and shifted by the brightness, then clipped to 0..255. \"\n",

    "            \"At the default the whole photo is squeezed into the 14 darkest values (0 to 13). Nothing is clipped, \"\n",

    "            \"so a fix can stretch it out again, but only those 14 shades survive, so the fixed photo looks \"\n",

    "            \"posterized. Pull the brightness below 0 and the shadows clip to pure black: that detail is gone \"\n",

    "            \"for good.\",\n",

    "    params=[slider(\"contrast\", 0.05, 0.01, 2.0, 0.01), slider(\"brightness\", 0, -128, 128, 1)])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "52cf2bc0",

   "metadata": {},

   "outputs": [],

   "source": [

    "def blur(img, ksize=21):\n",

    "    return cv2.GaussianBlur(img, (ksize, ksize), 0)\n",

    "\n",

    "add_step(blur, \"Blur\", \"break\",\n",

    "    summary=\"Blur the photo, like a camera out of focus.\",\n",

    "    explain=\"Each pixel becomes a weighted average of its neighbours. Fur, edges and texture, which the model \"\n",

    "            \"relies on, fade away. The kernel size must be odd so it has a centre pixel.\",\n",

    "    params=[slider(\"ksize\", 21, 3, 61, 2, \"kernel size\", odd=True)])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "ad4ad32a",

   "metadata": {},

   "outputs": [],

   "source": [

    "def add_noise(img, sigma=50):\n",

    "    rng = np.random.default_rng(0)  # fixed seed: the same noise on every run\n",

    "    noisy = img.astype(np.float32) + rng.normal(0, sigma, img.shape)\n",

    "    return np.clip(noisy, 0, 255).astype(np.uint8)\n",

    "\n",

    "add_step(add_noise, \"Noise\", \"break\",\n",

    "    summary=\"Add grain, like a cheap sensor at night.\",\n",

    "    explain=\"Random values are added to every pixel. People see straight through the grain; models \"\n",

    "            \"often do not.\",\n",

    "    params=[slider(\"sigma\", 50, 5, 120, 5, \"noise strength\")])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "2192dff9",

   "metadata": {},

   "outputs": [],

   "source": [

    "def salt_pepper(img, amount=0.1):\n",

    "    rng = np.random.default_rng(0)  # fixed seed: the same specks on every run\n",

    "    hit = rng.random(img.shape[:2])  # one random number per pixel\n",

    "    out = img.copy()\n",

    "    out[hit < amount / 2] = 0        # pepper: pure black\n",

    "    out[hit > 1 - amount / 2] = 255  # salt: pure white\n",

    "    return out\n",

    "\n",

    "add_step(salt_pepper, \"Salt & pepper noise\", \"break\", short=\"Salt & pepper\",\n",

    "    summary=\"Scatter pure black and white specks, like dust or dead pixels.\",\n",

    "    explain=\"A fraction of the pixels (the amount) is replaced by pure black or pure white; the rest are untouched. \"\n",

    "            \"Unlike grain, each speck is completely wrong, but the pixels around it are still right.\",\n",

    "    params=[slider(\"amount\", 0.1, 0.01, 0.5, 0.01, \"fraction of pixels\")])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "e11748f8",

   "metadata": {},

   "outputs": [],

   "source": [

    "def low_resolution(img, factor=8):\n",

    "    h, w = img.shape[:2]\n",

    "    small = cv2.resize(img, (max(1, w // factor), max(1, h // factor)), interpolation=cv2.INTER_AREA)\n",

    "    return cv2.resize(small, (w, h), interpolation=cv2.INTER_NEAREST)\n",

    "\n",

    "add_step(low_resolution, \"Low resolution\", \"break\", short=\"Low-res\",\n",

    "    summary=\"Throw away detail, like a tiny thumbnail blown back up.\",\n",

    "    explain=\"The photo is shrunk by the factor, then scaled back to its size. The image is the same size, \"\n",

    "            \"but most of the information is gone and the edges turn into blocks.\",\n",

    "    params=[slider(\"factor\", 8, 2, 32, 1)])"

   ]

  },

  {

   "cell_type": "markdown",

   "id": "4978f341",

   "metadata": {},

   "source": [

    "## Fix it: enhancement and restoration\n",

    "\n",

    "Classic image processing can undo some damage before the model sees the photo. **Enhancement** makes a photo easier\n",

    "to read (brighter, more contrast, sharper edges). **Restoration** tries to remove a known kind of damage (tilt,\n",

    "noise). They are off in the presets. Break the photo, switch a fix on, and watch how much of the answer comes back.\n",

    "\n",

    "A fix can only use what is left in the pixels. There is no fix for low resolution on purpose: once detail is thrown\n",

    "away, no filter can bring it back."

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "a7ae4b42",

   "metadata": {},

   "outputs": [],

   "source": [

    "def straighten(img, angle=-45):\n",

    "    h, w = img.shape[:2]\n",

    "    M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)\n",

    "    return cv2.warpAffine(img, M, (w, h))\n",

    "\n",

    "add_step(straighten, \"Straighten\", \"fix\", helps=[\"rotate\"],\n",

    "    summary=\"Rotate the photo back upright by a known angle.\",\n",

    "    explain=\"The same rotation as Rotate, in the other direction: -45 exactly undoes a 45 degree tilt. The animal \"\n",

    "            \"is upright again and the answer mostly comes back, but the corners that were cut off by the first \"\n",

    "            \"rotation stay black, because those pixels are gone.\",\n",

    "    params=[slider(\"angle\", -45, -180, 180, 5, \"angle (degrees)\")])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "3cdff0c6",

   "metadata": {},

   "outputs": [],

   "source": [

    "def gamma(img, gamma=0.5):\n",

    "    table = (255 * (np.arange(256) / 255) ** gamma).astype(np.uint8)  # new value for each old value\n",

    "    return cv2.LUT(img, table)\n",

    "\n",

    "add_step(gamma, \"Gamma correction\", \"fix\", short=\"Gamma\", helps=[\"darken\"],\n",

    "    summary=\"Brighten the dark tones much more than the bright ones.\",\n",

    "    explain=\"Every value v becomes 255 * (v / 255) ** gamma. With gamma below 1, dark values are lifted a lot and \"\n",

    "            \"bright ones barely move, so shadows open up without white areas burning out. On a dark photo it brings \"\n",

    "            \"the answer back almost fully, as long as the shadows were not clipped to black.\",\n",

    "    params=[slider(\"gamma\", 0.5, 0.2, 3.0, 0.05)])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "4e7b6f73",

   "metadata": {},

   "outputs": [],

   "source": [

    "def equalize(img):\n",

    "    ycc = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)  # Y = brightness, Cr and Cb = color\n",

    "    y = cv2.equalizeHist(np.ascontiguousarray(ycc[:, :, 0]))\n",

    "    return cv2.cvtColor(np.dstack([y, ycc[:, :, 1], ycc[:, :, 2]]), cv2.COLOR_YCrCb2RGB)\n",

    "\n",

    "add_step(equalize, \"Histogram equalization\", \"fix\", short=\"Equalize\", helps=[\"darken\"],\n",

    "    summary=\"Spread the brightness values over the whole 0..255 range.\",\n",

    "    explain=\"Each brightness level is moved so that the levels spread out over 0..255, in proportion to how many \"\n",

    "            \"pixels have them; the colors are left alone. It cannot invent new levels: a dim photo with only a few \"\n",

    "            \"dozen levels comes back with the same few dozen, spread apart (see the gaps in the histogram). \"\n",

    "            \"Sometimes that is enough for the model, and sometimes the harsh result makes the answer worse.\")"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "64427bd4",

   "metadata": {},

   "outputs": [],

   "source": [

    "def clahe(img, clip=4.0, tiles=8):\n",

    "    lab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)  # L = lightness, A and B = color\n",

    "    tool = cv2.createCLAHE(clipLimit=clip, tileGridSize=(tiles, tiles))\n",

    "    l = tool.apply(np.ascontiguousarray(lab[:, :, 0]))\n",

    "    return cv2.cvtColor(np.dstack([l, lab[:, :, 1], lab[:, :, 2]]), cv2.COLOR_LAB2RGB)\n",

    "\n",

    "add_step(clahe, \"CLAHE\", \"fix\", helps=[\"darken\"],\n",

    "    summary=\"Equalize contrast tile by tile, with a limit so noise is not blown up.\",\n",

    "    explain=\"Contrast Limited Adaptive Histogram Equalization splits the lightness into tiles and equalizes each \"\n",

    "            \"one, so a dark corner and a bright sky are both fixed. The clip limit caps how much contrast a tile \"\n",

    "            \"may gain, which keeps flat areas from turning into noise. On a dark photo it helps, but a little less \"\n",

    "            \"than plain gamma, because each tile is stretched on its own.\",\n",

    "    params=[slider(\"clip\", 4.0, 1.0, 8.0, 0.5, \"clip limit\"), slider(\"tiles\", 8, 2, 16, 1, \"tiles per side\")])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "cbfa1e10",

   "metadata": {},

   "outputs": [],

   "source": [

    "def denoise(img, h=8):\n",

    "    # Non-local means: average each pixel with pixels whose surrounding 7x7 patch looks alike,\n",

    "    # searching a 15x15 window around it.\n",

    "    return cv2.fastNlMeansDenoisingColored(np.ascontiguousarray(img), None, h, h, 7, 15)\n",

    "\n",

    "add_step(denoise, \"Non-local means denoise\", \"fix\", short=\"Denoise\", helps=[\"add_noise\"],\n",

    "    summary=\"Remove grain by averaging patches that look alike.\",\n",

    "    explain=\"For each pixel, similar-looking patches in a 15 by 15 neighbourhood are found and averaged, so random \"\n",

    "            \"grain cancels out while edges survive. The photo looks much cleaner, but the model often barely \"\n",

    "            \"changes its answer: YOLO gets a few objects back on some photos, and ResNet hardly needs it (a higher \"\n",

    "            \"h smooths away the fur it relies on). A cleaner picture for people is not always a better one for a \"\n",

    "            \"model. It is the slowest step in the lab.\",\n",

    "    params=[slider(\"h\", 8, 3, 40, 1, \"strength\")])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "03bdfff8",

   "metadata": {},

   "outputs": [],

   "source": [

    "def median_filter(img, ksize=5):\n",

    "    return cv2.medianBlur(np.ascontiguousarray(img), ksize)\n",

    "\n",

    "add_step(median_filter, \"Median filter\", \"fix\", short=\"Median\", helps=[\"salt_pepper\"],\n",

    "    summary=\"Replace each pixel by the middle value of its neighbours.\",\n",

    "    explain=\"Sort the pixels in a small square and keep the middle one. A black or white speck is almost never the \"\n",

    "            \"middle value, so it simply disappears, while edges stay sharp (unless the specks cover so much of the \"\n",

    "            \"photo that they become the middle value). Against grain it is a mixed bag: every pixel is a little \"\n",

    "            \"wrong, so YOLO finds a few more objects, but ResNet loses the fur texture it relies on.\",\n",

    "    params=[slider(\"ksize\", 5, 3, 15, 2, \"kernel size\", odd=True)])"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "99202eb5",

   "metadata": {},

   "outputs": [],

   "source": [

    "def sharpen(img, amount=1.5, sigma=3.0):\n",

    "    blurred = cv2.GaussianBlur(img, (0, 0), sigma)\n",

    "    return cv2.addWeighted(img, 1 + amount, blurred, -amount, 0)  # img + amount * (img - blurred)\n",

    "\n",

    "add_step(sharpen, \"Unsharp mask\", \"fix\", short=\"Sharpen\", helps=[\"blur\"],\n",

    "    summary=\"Boost edges by adding back the difference from a blurred copy.\",\n",

    "    explain=\"Blur a copy, subtract it from the photo to get only the edges, and add those edges back, amplified. \"\n",

    "            \"Edges that are still faintly there become crisp again, so the model gets part of its answer back; \"\n",

    "            \"detail the blur fully erased cannot return, and too much sharpening adds bright halos.\",\n",

    "    params=[slider(\"amount\", 1.5, 0.0, 5.0, 0.1), slider(\"sigma\", 3.0, 0.5, 10.0, 0.5, \"blur radius\")])"

   ]

  },

  {

   "cell_type": "markdown",

   "id": "fa672082",

   "metadata": {},

   "source": [

    "## Running a pipeline\n",

    "\n",

    "A pipeline is a list of steps: `{\"op\": step id, \"params\": {...}, \"enabled\": True}`. `run_step` runs one;\n",

    "`run_pipeline` runs them all and keeps every intermediate image."

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "e2d1e672",

   "metadata": {},

   "outputs": [],

   "source": [

    "def clean_params(step_id, params=None):\n",

    "    # Fill in defaults and keep every value inside its slider range (kernel sizes stay odd).\n",

    "    params = params or {}\n",

    "    out = {}\n",

    "    for p in STEPS[step_id][\"params\"]:\n",

    "        v = params.get(p[\"name\"], p[\"default\"])\n",

    "        if p[\"type\"] == \"int\":\n",

    "            v = min(p[\"max\"], max(p[\"min\"], int(round(float(v)))))\n",

    "            if p.get(\"odd\") and v % 2 == 0:\n",

    "                v += 1\n",

    "        else:\n",

    "            v = min(p[\"max\"], max(p[\"min\"], float(v)))\n",

    "        out[p[\"name\"]] = v\n",

    "    return out\n",

    "\n",

    "\n",

    "def run_step(img, step_id, params):\n",

    "    return STEPS[step_id][\"fn\"](img, **params)\n",

    "\n",

    "\n",

    "def run_pipeline(img, steps):\n",

    "    # img: the BGR image from load_image. Returns one (name, image) per step, starting with the input.\n",

    "    results = [(\"Load image\", img)]\n",

    "    for step in steps:\n",

    "        if not step.get(\"enabled\", True):\n",

    "            continue\n",

    "        img = run_step(img, step[\"op\"], clean_params(step[\"op\"], step.get(\"params\")))\n",

    "        results.append((STEPS[step[\"op\"]][\"name\"], img))\n",

    "    return results"

   ]

  },

  {

   "cell_type": "markdown",

   "id": "8d258447",

   "metadata": {},

   "source": [

    "## Models\n",

    "\n",

    "**ResNet50** (ImageNet, 1000 classes) classifies. **YOLO11s-seg** (COCO, 80 classes) finds, outlines and names every\n",

    "object. Weights are read from `weights/`, downloaded once by `scripts/fetch_models.py`."

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "9b1768a7",

   "metadata": {},

   "outputs": [],

   "source": [

    "import os\n",

    "from pathlib import Path\n",

    "\n",

    "HERE = Path(globals().get(\"__file__\", \"image_lab.ipynb\")).resolve().parent  # the backend folder\n",

    "WEIGHTS = HERE / \"weights\"\n",

    "os.environ.setdefault(\"TORCH_HOME\", str(WEIGHTS / \"torch\"))\n",

    "os.environ.setdefault(\"YOLO_OFFLINE\", \"1\")\n",

    "\n",

    "import torch\n",

    "from torchvision.models import ResNet50_Weights, resnet50\n",

    "\n",

    "LABELS = ResNet50_Weights.IMAGENET1K_V1.meta[\"categories\"]  # the 1000 ImageNet class names\n",

    "\n",

    "\n",

    "def load_resnet50():\n",

    "    return resnet50(weights=ResNet50_Weights.IMAGENET1K_V1).eval()\n",

    "\n",

    "\n",

    "def classify_resnet50(img, model):\n",

    "    # img: the pipeline's output, which should be float32 (3, 224, 224). It goes in exactly as it is, so a\n",

    "    # switched-off step really reaches the model. Returns the probability of every class.\n",

    "    x = torch.from_numpy(np.ascontiguousarray(img, dtype=np.float32))[None]  # add a batch axis\n",

    "    with torch.no_grad():\n",

    "        logits = model(x)\n",

    "    return logits.softmax(dim=1)[0].numpy()\n",

    "\n",

    "\n",

    "def top_k(probs, k=5):\n",

    "    best = np.argsort(probs)[::-1][:k]\n",

    "    return [(LABELS[i], round(float(probs[i]), 4)) for i in best]"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "f78c18c4",

   "metadata": {},

   "outputs": [],

   "source": [

    "def as_uint8_rgb(img):\n",

    "    # Undo float, CHW or gray layouts so any pipeline output can be shown or fed to YOLO.\n",

    "    if img.ndim == 3 and img.shape[0] == 3 and img.shape[2] != 3:\n",

    "        img = img.transpose(1, 2, 0)\n",

    "    if img.dtype != np.uint8:\n",

    "        img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)\n",

    "    if img.ndim == 2:\n",

    "        img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n",

    "    return np.ascontiguousarray(img)"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "a84cb348",

   "metadata": {},

   "outputs": [],

   "source": [

    "from ultralytics import YOLO\n",

    "\n",

    "\n",

    "def load_yolo():\n",

    "    return YOLO(str(WEIGHTS / \"yolo11s-seg.pt\"))\n",

    "\n",

    "\n",

    "def class_color(class_id):\n",

    "    # One fixed color per COCO class, identical on every screen.\n",

    "    hue = int(class_id * 0.618 % 1 * 180)\n",

    "    rgb = cv2.cvtColor(np.uint8([[[hue, 200, 220]]]), cv2.COLOR_HSV2RGB)[0, 0]\n",

    "    return tuple(int(c) for c in rgb)\n",

    "\n",

    "\n",

    "def draw_label(img, text, x, y, color):\n",

    "    font, scale, thick = cv2.FONT_HERSHEY_SIMPLEX, max(0.5, img.shape[1] / 1000), 1\n",

    "    (tw, th), base = cv2.getTextSize(text, font, scale, thick)\n",

    "    x, y = min(max(0, x), img.shape[1] - tw - 6), max(th + base + 4, y)\n",

    "    cv2.rectangle(img, (x, y - th - base - 4), (x + tw + 6, y), color, -1)\n",

    "    cv2.putText(img, text, (x + 3, y - base - 2), font, scale, (0, 0, 0), thick, cv2.LINE_AA)\n",

    "\n",

    "\n",

    "def segment_yolo(img, model, conf=0.25):\n",

    "    # img: RGB uint8 (H, W, 3). Returns an image with every object outlined and named,\n",

    "    # and one (class, confidence) per object.\n",

    "    result = model.predict(img[:, :, ::-1], conf=conf, verbose=False)[0]  # Ultralytics expects BGR\n",

    "    overlay = img.copy()\n",

    "    instances = []\n",

    "    if result.masks is None:\n",

    "        return overlay, instances\n",

    "    polygons = result.masks.xy\n",

    "    classes = [int(c) for c in result.boxes.cls.tolist()]\n",

    "    scores = result.boxes.conf.tolist()\n",

    "    for polygon, cls in zip(polygons, classes):  # fill every mask first, so labels stay on top\n",

    "        layer = overlay.copy()\n",

    "        cv2.fillPoly(layer, [polygon.astype(np.int32)], class_color(cls))\n",

    "        overlay = cv2.addWeighted(layer, 0.45, overlay, 0.55, 0)\n",

    "    for polygon, cls, score in zip(polygons, classes, scores):\n",

    "        pts = polygon.astype(np.int32)\n",

    "        if len(pts) == 0:\n",

    "            continue\n",

    "        cv2.polylines(overlay, [pts], True, class_color(cls), 2, cv2.LINE_AA)\n",

    "        top = pts[pts[:, 1].argmin()]\n",

    "        draw_label(overlay, f\"{result.names[cls]} {score:.0%}\", int(top[0]), int(top[1]), class_color(cls))\n",

    "        instances.append((result.names[cls], round(score, 3)))\n",

    "    return overlay, instances"

   ]

  },

  {

   "cell_type": "markdown",

   "id": "039b1d9c",

   "metadata": {},

   "source": [

    "## The two lines\n",

    "\n",

    "Preparation steps are on; break-it and fix-it steps are off. Switch one on (here: `\"enabled\": True`) to see what\n",

    "breaks, then switch on a fix to see what comes back.\n",

    "\n",

    "`best_fix` names, for each break, the fix that brings the answer back best on the line's default photo (measured,\n",

    "and checked by the tests). The app offers it first. A break that is missing there has no fix that reliably helps on\n",

    "that line: for noise the photo looks cleaner after Denoise, but the answer barely moves."

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "4a3b7b7b",

   "metadata": {},

   "outputs": [],

   "source": [

    "BREAKS = [{\"op\": op, \"enabled\": False}\n",

    "          for op in [\"rotate\", \"darken\", \"blur\", \"add_noise\", \"salt_pepper\", \"low_resolution\"]]\n",

    "FIXES = [{\"op\": op, \"enabled\": False}\n",

    "         for op in [\"straighten\", \"gamma\", \"equalize\", \"clahe\", \"denoise\", \"median_filter\", \"sharpen\"]]\n",

    "\n",

    "LINES = [\n",

    "    dict(id=\"classify\", name=\"Classify\", model=\"ResNet50\", default_image=\"pet-boxer\",\n",

    "         question=\"What animal is this?\",\n",

    "         task={\"type\": \"classify\"},\n",

    "         best_fix={\"rotate\": \"straighten\", \"darken\": \"gamma\", \"salt_pepper\": \"median_filter\"},\n",

    "         steps=[{\"op\": \"bgr_to_rgb\"}, *BREAKS, *FIXES,\n",

    "                {\"op\": \"resize_shorter\"}, {\"op\": \"center_crop\"}, {\"op\": \"normalize\"}, {\"op\": \"to_chw\"}]),\n",

    "    dict(id=\"segment\", name=\"Segment\", model=\"YOLO11s-seg\", default_image=\"coco-000000000049\",\n",

    "         question=\"What objects are here, and how many?\",\n",

    "         task={\"type\": \"segment\", \"conf\": 0.25},\n",

    "         best_fix={\"rotate\": \"straighten\", \"darken\": \"gamma\", \"blur\": \"sharpen\", \"salt_pepper\": \"median_filter\"},\n",

    "         steps=[{\"op\": \"bgr_to_rgb\"}, *BREAKS, *FIXES, {\"op\": \"letterbox\"}]),\n",

    "]"

   ]

  },

  {

   "cell_type": "markdown",

   "id": "a17e515d",

   "metadata": {},

   "source": [

    "## Try it\n",

    "\n",

    "These cells are tagged `demo`: they run here in the notebook, never in the web app."

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "5675e5ee",

   "metadata": {

    "tags": [

     "demo"

    ]

   },

   "outputs": [],

   "source": [

    "import matplotlib.pyplot as plt\n",

    "\n",

    "\n",

    "def show_steps(results, cols=4):\n",

    "    rows = (len(results) + cols - 1) // cols\n",

    "    fig, axes = plt.subplots(rows, cols, figsize=(4 * cols, 4 * rows))\n",

    "    for ax in np.ravel(axes):\n",

    "        ax.axis(\"off\")\n",

    "    for ax, (name, img) in zip(np.ravel(axes), results):\n",

    "        ax.imshow(as_uint8_rgb(img))\n",

    "        ax.set_title(f\"{name}\\n{img.shape} {img.dtype}\", fontsize=9)\n",

    "    plt.tight_layout()\n",

    "    plt.show()\n",

    "\n",

    "\n",

    "results = run_pipeline(load_image(\"data/pets/boxer.jpg\"), LINES[0][\"steps\"])\n",

    "show_steps(results)"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "4cc31c8f",

   "metadata": {

    "tags": [

     "demo"

    ]

   },

   "outputs": [],

   "source": [

    "model = load_resnet50()\n",

    "for label, prob in top_k(classify_resnet50(results[-1][1], model)):\n",

    "    print(f\"{prob:6.1%}  {label}\")"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": null,

   "id": "171a98ad",

   "metadata": {

    "tags": [

     "demo"

    ]

   },

   "outputs": [],

   "source": [

    "from collections import Counter\n",

    "\n",

    "results = run_pipeline(load_image(\"data/coco/000000000049.jpg\"), LINES[1][\"steps\"])\n",

    "overlay, instances = segment_yolo(results[-1][1], load_yolo())\n",

    "print(Counter(name for name, _ in instances))\n",

    "plt.figure(figsize=(8, 8)); plt.imshow(overlay); plt.axis(\"off\"); plt.show()"

   ]

  }

 ],

 "metadata": {

  "kernelspec": {

   "display_name": "Python (imgdemo)",

   "language": "python",

   "name": "imgdemo"

  },

  "language_info": {

   "name": "python"

  }

 },

 "nbformat": 4,

 "nbformat_minor": 5

}