File size: 84,946 Bytes
61a2a11
6db455d
61a2a11
a850477
61a2a11
073e1ec
61a2a11
073e1ec
daa230d
e8ce19b
f749287
fa3db93
073e1ec
f749287
073e1ec
 
 
 
 
7e166d0
073e1ec
 
 
7e166d0
073e1ec
 
7e166d0
073e1ec
 
61a2a11
3a6d54d
61a2a11
 
 
 
 
5a39fae
 
e8ce19b
 
6db455d
1992f31
6db455d
e8ce19b
6db455d
 
e8ce19b
6db455d
f749287
 
 
6db455d
f749287
 
 
e8ce19b
f749287
abf8b12
f749287
041ccf6
6db455d
e8ce19b
6db455d
e8ce19b
6db455d
f749287
 
6db455d
e8ce19b
6db455d
 
 
e8ce19b
 
 
 
 
 
6db455d
 
e8ce19b
6db455d
 
 
 
e8ce19b
6db455d
 
 
 
 
 
e8ce19b
6db455d
1356e3f
e8ce19b
48aa073
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1356e3f
5981968
 
 
1356e3f
5981968
 
 
 
1356e3f
5981968
 
 
 
 
 
 
5dfeb3d
0902eb1
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105bc86
5981968
 
 
4e659cc
5981968
 
 
 
 
 
 
 
 
 
 
1356e3f
5981968
 
 
 
1356e3f
5981968
 
1356e3f
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1356e3f
5981968
 
 
 
4e659cc
5981968
 
 
 
1356e3f
5981968
 
1356e3f
5981968
 
 
 
 
 
1356e3f
5dd8744
5981968
1356e3f
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d87026
5981968
9d87026
 
 
5981968
 
 
 
9d87026
5981968
9d87026
 
 
5981968
9d87026
a1d70f8
3c1d04d
5dfeb3d
a1d70f8
9d87026
9b6035e
 
 
 
00943b9
9d87026
 
ffc2cf7
9d87026
 
 
 
 
 
 
 
5981968
9d87026
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dd8744
 
9b6035e
 
 
5dd8744
9b6035e
9d87026
 
c376570
aa73d1f
 
25cf647
9d87026
 
 
 
 
 
 
 
 
 
 
 
8a2a600
 
 
9d87026
 
 
 
 
 
 
5981968
9d87026
 
 
 
5981968
 
9d87026
5981968
5dd8744
5981968
 
 
 
 
 
 
5dd8744
ab06849
 
9dd01fc
4e659cc
5981968
 
 
 
 
 
 
1cc296c
 
63c398d
 
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e659cc
1356e3f
5981968
 
 
 
 
740ff76
5981968
 
 
 
 
 
 
 
 
 
1356e3f
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1356e3f
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740ff76
4e659cc
740ff76
ec9b93f
4e659cc
5981968
 
 
 
 
 
 
 
ed472aa
 
5981968
ed472aa
 
 
 
5981968
ed472aa
 
105bc86
6109ac9
5981968
 
 
 
 
f5de775
5981968
9578715
 
5981968
 
 
58d3997
f5de775
 
58d3997
 
 
 
5981968
 
 
 
105bc86
5981968
 
 
 
 
 
 
105bc86
5981968
 
 
3f93994
 
 
045fdda
8cad168
286da5e
f9ce97e
3f93994
80cc578
 
3f93994
 
 
f9ce97e
105bc86
f388846
5981968
421ffe3
5981968
 
 
 
 
421ffe3
796c226
740ff76
5981968
286da5e
421ffe3
f5de775
740ff76
4e659cc
5981968
045fdda
796c226
41db10e
dfd2a1f
41db10e
ab06849
421ffe3
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b3661f
5981968
9a68db5
 
 
f1f853a
9a68db5
 
 
 
 
 
 
9c09208
9a68db5
9c09208
9a68db5
 
0b3661f
862d1fa
 
 
 
5981968
862d1fa
 
 
 
5981968
862d1fa
 
 
 
 
 
5981968
862d1fa
 
 
5981968
862d1fa
 
 
 
 
5981968
862d1fa
 
 
 
 
5981968
 
862d1fa
 
 
5981968
862d1fa
 
 
1356e3f
862d1fa
 
 
 
5981968
862d1fa
5981968
2d965c6
 
 
 
 
 
 
 
 
 
 
 
 
5981968
2d965c6
 
 
5981968
2d965c6
 
 
 
 
 
 
 
 
 
 
 
 
5981968
2d965c6
 
 
5981968
2d965c6
 
 
 
 
5981968
2d965c6
 
 
 
 
5981968
2d965c6
 
 
 
 
 
 
 
 
1356e3f
 
f1ee312
 
 
5981968
f1ee312
 
 
 
 
 
 
 
5981968
f1ee312
 
 
 
 
5981968
f1ee312
 
5981968
f1ee312
 
 
 
5981968
f1ee312
 
a0a84b3
5981968
f1ee312
 
a0a84b3
5981968
f1ee312
 
a0a84b3
5981968
f1ee312
649947a
a0a84b3
649947a
5981968
0b3661f
f1ee312
 
5981968
f1ee312
 
 
 
2b65f18
 
 
 
 
 
 
7019011
1c81a46
7019011
1c81a46
7019011
1c81a46
 
4a2ffe6
93b98d4
2037ae9
 
 
1c81a46
 
 
7019011
 
 
1c81a46
 
 
 
 
 
 
 
 
 
2b65f18
1356e3f
5981968
0b3661f
6ef28c0
5981968
2b65f18
5981968
1c81a46
5981968
 
 
 
 
421ffe3
6621478
5981968
 
 
 
 
 
 
7e1ad8c
 
 
 
 
5981968
c92ac43
 
 
 
 
 
 
 
7e1ad8c
c92ac43
 
7e1ad8c
c92ac43
7e1ad8c
 
c92ac43
 
7e1ad8c
 
 
5981968
 
 
 
 
c1196be
 
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e659cc
5981968
 
4e659cc
5981968
ee78137
5981968
d2da557
336f598
5981968
c3a1b22
 
 
5981968
 
 
336f598
5981968
 
 
c3a1b22
d2da557
6988dd8
 
 
5981968
6988dd8
 
 
5981968
421ffe3
ee78137
ec1a06a
421ffe3
0b3661f
1356e3f
1c81a46
2b65f18
ee78137
5981968
2b65f18
5981968
 
1e6ef05
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
1e6ef05
0b3661f
5981968
 
 
 
 
 
ee78137
5981968
 
88706fc
5981968
88706fc
 
 
 
 
 
 
 
 
 
 
2c7d8e9
88706fc
 
 
 
 
 
5981968
 
 
 
1356e3f
5981968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
529ee05
 
 
1356e3f
529ee05
b417ab1
5981968
478ac9e
 
 
2e982b5
5981968
 
 
1c5a6aa
5981968
421ffe3
5981968
 
1356e3f
5981968
 
 
 
 
 
 
 
 
 
 
2b65f18
 
5981968
36af379
5981968
4a2ffe6
 
5981968
4a2ffe6
5981968
 
4a2ffe6
5981968
1356e3f
4a2ffe6
5981968
 
 
1356e3f
5981968
 
 
 
67ffca8
5981968
67ffca8
5981968
 
 
 
 
 
 
 
 
1356e3f
5981968
 
1356e3f
5981968
 
 
 
 
 
 
59f8710
5981968
5a77243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59f8710
 
1356e3f
5a77243
 
 
5981968
5a77243
 
 
 
 
5981968
5a77243
 
 
 
 
 
 
 
f499d42
5a77243
74e4b35
17727b2
 
 
 
 
 
74e4b35
 
ecc91ab
74e4b35
 
 
 
 
 
 
 
 
 
ecc91ab
74e4b35
 
 
 
 
 
 
 
 
 
 
 
 
6439728
74e4b35
 
 
 
 
59f8710
 
 
 
c546297
59f8710
 
c546297
59f8710
 
c546297
59f8710
 
 
c546297
59f8710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6621478
519b893
 
 
 
59f8710
519b893
 
 
 
 
e9345f5
519b893
 
59f8710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ac2546
9dfacd3
59f8710
 
 
 
 
 
 
 
 
 
 
 
 
5981968
 
 
b85b028
5981968
b85b028
74e4b35
b85b028
 
d2da557
2ca3107
b85b028
5981968
 
 
 
 
b85b028
 
 
d756400
b85b028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5981968
 
 
 
 
 
b85b028
5981968
 
d2da557
5981968
b85b028
 
 
 
 
 
5981968
 
b85b028
 
17727b2
2cb2270
17727b2
5981968
1356e3f
5981968
1356e3f
5981968
 
 
 
 
 
 
 
 
 
 
f749287
5981968
 
 
 
 
1356e3f
5981968
1356e3f
f749287
6db455d
 
f749287
 
 
 
6db455d
e8ce19b
6db455d
f749287
e8ce19b
6db455d
 
 
e8ce19b
6db455d
 
 
f749287
6db455d
 
f749287
e8ce19b
f749287
6db455d
e8ce19b
61a2a11
 
 
f749287
 
 
61a2a11
7e166d0
5a39fae
61a2a11
5a39fae
61a2a11
e8ce19b
5a39fae
 
 
f749287
 
 
5a39fae
 
e8ce19b
5a39fae
e8ce19b
 
5a39fae
 
e8ce19b
5a39fae
 
e8ce19b
5a39fae
 
 
 
 
e8ce19b
5a39fae
 
 
 
 
e8ce19b
5a39fae
7e166d0
61a2a11
d18cc2e
f749287
 
 
61a2a11
 
 
 
d18cc2e
61a2a11
 
 
 
7e166d0
61a2a11
 
f749287
 
 
61a2a11
 
 
f749287
61a2a11
d18cc2e
8d8dd67
 
 
 
 
 
 
 
1162791
29daa53
8d8dd67
 
 
 
 
 
 
 
61a2a11
 
 
 
7e166d0
7bbb34d
d18cc2e
f749287
 
 
7bbb34d
 
e8ce19b
7bbb34d
202d583
e8ce19b
7bbb34d
 
e8ce19b
336c145
7bbb34d
 
d18cc2e
7bbb34d
 
336c145
5a39fae
 
 
f749287
 
 
5a39fae
 
 
 
e8ce19b
5a39fae
e8ce19b
5a39fae
e8ce19b
5a39fae
f749287
5a39fae
 
 
6db455d
5a39fae
 
 
e8ce19b
5a39fae
 
f749287
e8ce19b
5a39fae
 
e8ce19b
5a39fae
 
e8ce19b
5a39fae
 
e8ce19b
1fd9dad
5a39fae
e8ce19b
5a39fae
 
 
 
 
 
 
 
 
e8ce19b
5a39fae
 
 
 
 
1fd9dad
ffb4be7
 
 
 
f749287
 
 
 
 
e8ce19b
ffb4be7
 
f749287
 
 
 
 
d761a9d
ffb4be7
 
f749287
 
 
 
 
d761a9d
f749287
 
 
 
 
 
 
d761a9d
61a2a11
7e166d0
d18cc2e
61a2a11
 
 
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
import torch
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
from controlnet_aux import OpenposeDetector
from PIL import Image, ImageFilter, ImageEnhance  # NEU: ImageEnhance für Kontrast
import random
import cv2
import numpy as np
import gradio as gr
import torch.nn.functional as F
from transformers import Sam2Model, Sam2Processor
from scipy import ndimage
from skimage import measure, morphology

# === CONTROLNET FORTSCHRITTS-CALLBACK (Für Gradio-UI) ===
class ControlNetProgressCallback:
    def __init__(self, progress, total_steps):
        self.progress = progress
        self.total_steps = total_steps
        self.current_step = 0

    def __call__(self, pipe, step_index, timestep, callback_kwargs):
        self.current_step = step_index + 1
        progress_percentage = self.current_step / self.total_steps

        if self.progress is not None:
            self.progress(progress_percentage, desc=f"ControlNet: Schritt {self.current_step}/{self.total_steps}")

        print(f"ControlNet Fortschritt: {self.current_step}/{self.total_steps} ({progress_percentage:.1%})")
        return callback_kwargs


class ControlNetProcessor:
    def __init__(self, device="cuda", torch_dtype=torch.float32):
        self.device = device
        self.torch_dtype = torch_dtype
        self.pose_detector = None
        self.midas_model = None
        self.midas_transform = None
        self.sam_processor = None
        self.sam_model = None
        self.sam_initialized = False

    def _lazy_load_sam(self):
        """Lazy Loading von SAM 2 über 🤗 Transformers API"""
        if self.sam_initialized:
            return True

        try:
            print("#" * 80)
            print("# 🔄 LADE SAM 2 (Segment Anything Model 2)")
            print("#" * 80)
            model_id = "facebook/sam2-hiera-tiny"
            
            print(f"📥 Modell-ID: {model_id}")
            print(f"📥 Lade Processor...")
            self.sam_processor = Sam2Processor.from_pretrained(model_id)
            print(f"📥 Lade Modell...")
            self.sam_model = Sam2Model.from_pretrained(model_id, torch_dtype=torch.float32).to(self.device)
            self.sam_model.eval()
            
            self.sam_initialized = True
            print("✅ SAM 2 erfolgreich geladen (via Transformers)")
            return True

        except Exception as e:
            print(f"❌ FEHLER beim Laden von SAM 2: {str(e)[:200]}")
            self.sam_initialized = True
            return False

    def _validate_bbox(self, image, bbox_coords):
        """Validiert und korrigiert BBox-Koordinaten"""
        width, height = image.size

        if isinstance(bbox_coords, (list, tuple)) and len(bbox_coords) == 4:
            x1, y1, x2, y2 = bbox_coords
        else:
            x1, y1, x2, y2 = bbox_coords

        x1, x2 = min(x1, x2), max(x1, x2)
        y1, y2 = min(y1, y2), max(y1, y2)

        x1 = max(0, min(x1, width - 1))
        y1 = max(0, min(y1, height - 1))
        x2 = max(0, min(x2, width - 1))
        y2 = max(0, min(y2, height - 1))

        if x2 - x1 < 10 or y2 - y1 < 10:
            size = min(width, height) * 0.3
            x1 = max(0, width/2 - size/2)
            y1 = max(0, height/2 - size/2)
            x2 = min(width, width/2 + size/2)
            y2 = min(height, height/2 + size/2)

        return int(x1), int(y1), int(x2), int(y2)
            

    def create_sam_mask(self, image, bbox_coords, mode, is_front_face=False, is_back_head=False):
        """
        ERWEITERTE Funktion: Erstellt präzise Maske mit SAM 2
        """
        try:
            print("#" * 80)
            print("# 🎯 STARTE SAM 2 SEGMENTIERUNG")
            print("#" * 80)
            print(f"📐 Eingabebild-Größe: {image.size}")
            print(f"🎛️  Ausgewählter Modus: {mode}")
            
            # ============================================================
            # VORBEREITUNG FÜR ALLE MODI
            # ============================================================
            original_image = image
            
            # 1. SAM2 laden
            if not self.sam_initialized:
                print("📥 SAM 2 ist noch nicht geladen, starte Lazy Loading...")
                self._lazy_load_sam()

            if self.sam_model is None or self.sam_processor is None:
                print("⚠️ SAM 2 Model nicht verfügbar, verwende Fallback")
                return self._create_rectangular_mask(image, bbox_coords, mode)

            # 2. Validiere BBox
            x1, y1, x2, y2 = self._validate_bbox(image, bbox_coords)
            original_bbox = (x1, y1, x2, y2)
            print(f"📏 Original-BBox Größe: {x2-x1} × {y2-y1} px")
            
            # ============================================================
            # BLOCK 1: ENVIRONMENT_CHANGE
            # ============================================================
            if mode == "environment_change":
                print("-" * 60)
                print("🌳 MODUS: ENVIRONMENT_CHANGE")
                print("-" * 60)
                

                # Der Prozessor von SAM erwartet ein NumPy-Array kein PIL
                image_np = np.array(image.convert("RGB"))

                # Packt die BBox-Koordinaten in eine 3D-Liste
                input_boxes = [[[x1, y1, x2, y2]]]

                # Aufruf des SAM-Prozessors mit Originalbild in Form NumPy-Array und BBox.Der Processor verarbeitet Bild und BBox 
                # in die für SAM erforderlichen Tensoren und speichert sie in inputs.
                inputs = self.sam_processor(
                    image_np, 
                    input_boxes=input_boxes,
                    return_tensors="pt"
                ).to(self.device)    # Ohne .to(self.device) werden die Tensoren standardmäßig im CPU-RAM erzeugt und gespeichert! Da GPU-Fehler!

                print(f"   - 'input_boxes' Shape: {inputs['input_boxes'].shape}")

                # SAM2 Vorhersage
                print("-" * 60)
                print("🧠 SAM 2 INFERENZ (Vorhersage)")
                with torch.no_grad():
                    print("   Führe Vorhersage durch...")
                    outputs = self.sam_model(**inputs)   #führt die Segmentierung mit SAM aus
                    print(f"✅ Vorhersage abgeschlossen")
                    print(f"   Anzahl der Vorhersagemasken: {outputs.pred_masks.shape[2]}")               

                num_masks = outputs.pred_masks.shape[2]
                print(f"   SAM lieferte {num_masks} verschiedene Masken")  

                # Sammlung aller Masken in all_masks
                all_masks = []

                for i in range(num_masks):
                    single_mask = outputs.pred_masks[:, :, i, :, :]
                    resized_mask = F.interpolate(
                        single_mask,
                        size=(image.height, image.width),
                        mode='bilinear',
                        align_corners=False
                    ).squeeze()
        
                    mask_np = resized_mask.sigmoid().cpu().numpy()  #wandelt Modellausgaben in Wahrscheinlichkeiten und bewegt Daten von GPU nach CPU
                    all_masks.append(mask_np) #fügt die aktuelle Maske der Liste all_masks hinzu


                bbox_center = ((x1 + x2) // 2, (y1 + y2) // 2)
                bbox_area = (x2 - x1) * (y2 - y1)
                print(f"   Erwartetes BBox-Zentrum: {bbox_center}")
                print(f"   Erwartete BBox-Fläche: {bbox_area:,} Pixel")
                
                print("🤔 HEURISTIK: Beste Maske auswählen")
                best_mask_idx = 0
                best_score = -1
                
                # Alle 3 Masken analysieren (OHNE sie alle zu skalieren!)
                for i in range(num_masks):                         
                    mask_np_temp = all_masks[i] #verwende Maske auf Original-Bildgröße
                    
                    # Adaptive Vor-Filterung (prüft ob Maske überhaupt gültig ist)
                    mask_max = mask_np_temp.max()
                    if mask_max < 0.3:
                        continue  # Maske überspringen
                    
                    adaptive_threshold = max(0.3, mask_max * 0.7)
                    mask_binary = (mask_np_temp > adaptive_threshold).astype(np.uint8)

                    # wenn nur schwarze Pixel (keine Segmentierung) nimm die nächste Maske
                    if np.sum(mask_binary) == 0:
                        print(f"   ❌ Maske {i+1}: Keine Pixel nach adaptive_threshold {adaptive_threshold:.3f}")
                        continue

                    # Heuristik-Berechnung
                    mask_area_pixels = np.sum(mask_binary)

                    #Berechnung von Überlappung SAM-Maske und ursprünglicher BBox
                    bbox_mask = np.zeros((image.height, image.width), dtype=np.uint8)
                    bbox_mask[y1:y2, x1:x2] = 1
                        
                    overlap = np.sum(mask_binary & bbox_mask)
                    bbox_overlap_ratio = overlap / np.sum(bbox_mask) if np.sum(bbox_mask) > 0 else 0
                        
                    # Schwerpunkt berechnen
                    y_coords, x_coords = np.where(mask_binary > 0)
                    if len(y_coords) > 0:
                        centroid_y = np.mean(y_coords)
                        centroid_x = np.mean(x_coords)
                        centroid_distance = np.sqrt((centroid_x - bbox_center[0])**2 + (centroid_y - bbox_center[1])**2)
                        normalized_distance = centroid_distance / max(image.width, image.height)
                    else:
                        normalized_distance = 1.0
                        
                    # Flächen-Ratio
                    area_ratio = mask_area_pixels / bbox_area
                    area_score = 1.0 - min(abs(area_ratio - 1.0), 1.0)
                        
                    # Konfidenz
                    confidence_score = mask_max
                        
                    # Standard-Score
                    score = (
                        bbox_overlap_ratio * 0.4 +
                        (1.0 - normalized_distance) * 0.25 +
                        area_score * 0.25 +
                        confidence_score * 0.1
                    )
                        
                    print(f"   📊 STANDARD-SCORES für Maske {i+1}:")
                    print(f"     • BBox-Überlappung: {bbox_overlap_ratio:.3f}")
                    print(f"     • Zentrums-Distanz: {centroid_distance if 'centroid_distance' in locals() else 'N/A'}")
                    print(f"     • Flächen-Ratio: {area_ratio:.3f}")
                    print(f"     • GESAMTSCORE: {score:.3f}")
                    
                    if score > best_score:
                        best_score = score
                        best_mask_idx = i
                        print(f"     🏆 Neue beste Maske: Nr. {i+1} mit Score {score:.3f}")
                
                print(f"✅ Beste Maske ausgewählt: Nr. {best_mask_idx+1} mit Score {best_score:.3f}")
                
                # Beste Maske verwenden - mask_np beste Maske
                mask_np = all_masks[best_mask_idx]

                max_val = mask_np.max()
                print(f"   🔍 Maximaler SAM-Konfidenzwert der besten Maske: {max_val:.3f}")

                if max_val < 0.6:
                    dynamic_threshold = 0.3
                    print(f"   ⚠️  SAM ist unsicher (max_val={max_val:.3f} < 0.6)")
                else:
                    dynamic_threshold = max_val * 0.85          
                    print(f"   ✅ SAM ist sicher (max_val={max_val:.3f} >= 0.6)")

                # Binärmaske erstellen in Originalgröße
                mask_array = (mask_np > dynamic_threshold).astype(np.uint8) * 255

                # Fallback bei leerer Maske, der höchste Wert ist 0 also schwarz
                if mask_array.max() == 0:
                    print("   ⚠️  Maske leer, erstelle rechteckige Fallback-Maske")
                    mask_array = np.zeros((512, 512), dtype=np.uint8) * 255  # weiße 512x512-Maske
                    
                    # Skaliere BBox auf 512x512
                    scale_x = 512 / image.width
                    scale_y = 512 / image.height
                    fb_x1 = int(x1 * scale_x)
                    fb_y1 = int(y1 * scale_y)
                    fb_x2 = int(x2 * scale_x)
                    fb_y2 = int(y2 * scale_y)

                    # Schwarzes Rechteck für Person bzw. BBox
                    cv2.rectangle(mask_array, (fb_x1, fb_y1), (fb_x2, fb_y2), 0, -1) 

                # Damit wird die Rohmaske für die UI-Anzeige gespeichert
                raw_mask_array = mask_array.copy()     

                ##########################################################
                #   POSTPROCESSING
                ##########################################################
                print("🌳 ENVIRONMENT-CHANGE POSTPROCESSING")   
        
                # Konvertierung zu PIL, hochskalieren auf Originalgröße (korrekte Überlagerung mit O-Bild), 
                # Konvertierung NumPy für weitere Verarbeitung da mathematisch korrekter als PIL.
                if image.size != original_image.size:  #Vergleich SAM-Maskengröße und Original-Bildgröße
                    print(f"   ⚠️  Bildgröße angepasst: {image.size}{original_image.size}")
                    temp_mask = Image.fromarray(mask_array).convert("L")  #wandelt NumPy-Array in PIL-Bild
                    temp_mask = temp_mask.resize(original_image.size, Image.Resampling.NEAREST)  #skaliert auf Originalgröße
                    mask_array = np.array(temp_mask)  #np. heißt mache aus PIL-Image wieder numPy-Array
                    print(f"   ✅ Maske auf Originalgröße skaliert: {mask_array.shape}")

                
                working_mask = mask_array.copy()  # Person = Weiß, Hintergrund = Schwarz  - working_mask muß vor Nutzung definiert werden! 
                print(f"working_mask shape: {working_mask.shape}")


                # DILATE auf der weißen Person - dadurch wird Person etwas vergrößert
                kernel_dilate = np.ones((5, 5), np.uint8)               
                working_mask = cv2.dilate(working_mask, kernel_dilate, iterations=1)
                print(f"   ✅ Dilate (5x5) - Person leicht erweitert")
             

                # MORPH_CLOSE auf dem schwarzen Hintergrund (feine Löcher)- kleiner Kernel filigrane Heranarbeitung an Person,
                # es werden aber auch nur kleine Löcher in Umgebung von weiß nach schwarz geändert!
                kernel_close_small = np.ones((3, 3), np.uint8)
                working_mask = cv2.morphologyEx(working_mask, cv2.MORPH_CLOSE, kernel_close_small, iterations=1)
                print(f"   ✅ MORPH_CLOSE (3x3) - Feine Löcher im Hintergrund geschlossen")

                
                # KONTURENFILTER auf der weißen Person - arbeitet filigraner als MORPH-CLOSE
                # Finde Konturen (nur äußere)
                contours, _ = cv2.findContours(working_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
                if len(contours) > 0:
                    # Finde die größte Kontur (sollte die Person sein)
                    largest_contour = max(contours, key=cv2.contourArea)
            
                    # Erstelle eine saubere Maske mit nur der größten Kontur
                    clean_mask = np.zeros_like(working_mask)
                    cv2.drawContours(clean_mask, [largest_contour], -1, 255, -1)
            
                    # Optional: Kleine weiße Punkte IN der Person entfernen
                    # Dazu invertieren wir temporär, um "Löcher" (schwarze Pixel) in der Person zu finden
                    temp_inverted = 255 - clean_mask
                    hole_contours, _ = cv2.findContours(temp_inverted, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
            
                    for hole in hole_contours:
                        area = cv2.contourArea(hole)
                        if area < 100:  # Sehr kleine Löcher füllen
                            cv2.drawContours(clean_mask, [hole], -1, 255, -1)
            
                    working_mask = clean_mask
                    print(f"   ✅ Konturenfilter - Größte Kontur behalten, {len(contours)-1} kleine entfernt")


                #Inpaint darf auch nur eine schwarz/weiß Maske (Binärmaske 0,255) bekommen. Bei
                #weichen/grauen Pixeln könnte Inpaint etwas anderes generieren.          
                inpaint_binary_mask = working_mask.copy() #Person weiß
                #Invertieren da SAM segmentierte Person/Gegenstand weiß ausgibt
                inpaint_binary_mask = 255 - inpaint_binary_mask
                

                # Gaussian-BLUR für weiche Kanten für Composition
                #working_mask = cv2.GaussianBlur(working_mask, (5, 5), 1.2)
                working_mask = cv2.GaussianBlur(working_mask, (7, 7), 1.5)
                print(f"   ✅ Gaussian Blur (7x7 , sigma=1.5) für weiche Kanten")

            

                # GAMMA-Korrektur für präzisere Ränder
                working_mask_float = working_mask.astype(np.float32) / 255.0
                working_mask_float = np.clip(working_mask_float, 0.0, 1.0)
                working_mask_float = working_mask_float ** 0.85  # Gamma 0.85
                working_mask = (working_mask_float * 255).astype(np.uint8)
                print(f"   ✅ Gamma-Korrektur (0.85) gegen milchige Ränder")



                # Erst binäre Maske erzeugen und dann invertieren
                binary_mask = (working_mask > 128).astype(np.uint8) * 255 
                final_mask = 255 - binary_mask
                print(f"   ✅ Finale Invertierung für environment_change")


                # Qualitätskontrolle - Debug
                white_pixels = np.sum(final_mask > 127)
                black_pixels = np.sum(final_mask <= 127)
                total_pixels = final_mask.size
        
                print(f"   📊 FINALE MASKE:")
                print(f"     • Weiße Pixel (Hintergrund): {white_pixels:,} ({white_pixels/total_pixels*100:.1f}%)")
                print(f"     • Schwarze Pixel (Person): {black_pixels:,} ({black_pixels/total_pixels*100:.1f}%)")
                    
                    
                # Zurück zu PIL Image
                mask = Image.fromarray(final_mask).convert("L")
                raw_mask = Image.fromarray(raw_mask_array).convert("L")
                inpaint_binary_pil = Image.fromarray(inpaint_binary_mask).convert("L")

                print("#" * 80)
                print(f"✅ SAM 2 SEGMENTIERUNG ABGESCHLOSSEN")
                print(f"📐 Finale Maskengröße: {mask.size}")
                print(f"🎛️  Verwendeter Modus: {mode}")
                print("#" * 80)            
                            
                return mask, raw_mask, inpaint_binary_pil
                
                # in mask steht die invertierte nachbearbeitete Maske, in raw_mask die Rohmaske.Wichtig: mask (SAM-Maske) 
                # muß immer in Originalgröße zurück! in inpaint_binary_pil steht die harte, nachgearbeitete Binärmaske in Originalgröße
                
            # ============================================================
            # BLOCK 2: FOCUS_CHANGE
            # ============================================================
            elif mode == "focus_change":
                print("-" * 60)
                print("🎯 MODUS: FOCUS_CHANGE (OPTIMIERT)")
                print("-" * 60)

                # Originalgröße speichern
                # original_size = image.size
                # print(f"💾 Originalgröße gespeichert: {original_size}")
                
                # Konvertierung O-Bild in NumPy-Array für SAM
                image_np = np.array(image.convert("RGB"))
                
                #  Packt die BBox-Koordinaten in eine 3D-Liste
                input_boxes = [[[x1, y1, x2, y2]]]
                
                # Nur Mittelpunkt als positiver Prompt
                center_x = (x1 + x2) // 2
                center_y = (y1 + y2) // 2
                input_points = [[[[center_x, center_y]]]]  # NUR EIN PUNKT in 4D-Liste
                input_labels = [[[1]]]  # Markiert Punkt als Positiver Prompt also der Bereich muß segmentiert werden
                
                print(f"   🎯 SAM-Prompt: BBox [{x1},{y1},{x2},{y2}]")
                print(f"   👁️  Punkt: Nur Mitte ({center_x},{center_y})")
                
                # SAM Inputs vorbereiten
                inputs = self.sam_processor(
                    image_np, 
                    input_boxes=input_boxes,
                    input_points=input_points,
                    input_labels=input_labels,
                    return_tensors="pt"
                ).to(self.device)
                
                # SAM Vorhersage (alle 3 Masken)
                print("🧠 SAM 2 INFERENZ (3 Masken-Varianten)")
                with torch.no_grad():
                    print("   Führe Vorhersage durch...")
                    outputs = self.sam_model(**inputs)
                    print(f"✅ Vorhersage abgeschlossen")
                    print(f"   Anzahl der Vorhersagemasken: {outputs.pred_masks.shape[2]}")

                num_masks = outputs.pred_masks.shape[2]
                

                # Sammlung aller Masken in all_masks
                all_masks = []

                for i in range(num_masks):
                    single_mask = outputs.pred_masks[:, :, i, :, :]
                    # Interpolation auf Originalgröße
                    resized_mask = F.interpolate(
                        single_mask,
                        size=(image.height, image.width),
                        mode='bilinear',
                        align_corners=False
                    ).squeeze()
        
                    mask_np = resized_mask.sigmoid().cpu().numpy()
                    all_masks.append(mask_np) #fügt die aktuelle Maske der Liste all_masks hinzu
                

                # BBox-Information für Heuristik
                bbox_center = ((x1 + x2) // 2, (y1 + y2) // 2)
                bbox_area = (x2 - x1) * (y2 - y1)
                
                print("🤔 HEURISTIK: Beste Maske auswählen")
                best_mask_idx = 0
                best_score = -1
                
                # Alle 3 Masken analysieren
                for i in range(num_masks):
                    # Maske in Original-Bildgröße -vorher interpolate- analysieren

                    mask_np_temp = all_masks[i]
                    
                    # Adaptive Vor-Filterung (prüft ob Maske überhaupt gültig ist)
                    mask_max = mask_np_temp.max()
                    if mask_max < 0.3:
                        continue  # Maske überspringen
                    
                    adaptive_threshold = max(0.3, mask_max * 0.7)
                    mask_binary = (mask_np_temp > adaptive_threshold).astype(np.uint8)

                    # wenn nur schwarze Pixel (keine Segmentierung) nimm die nächste Maske
                    if np.sum(mask_binary) == 0:
                        continue
                    
                    # Heuristik-Berechnung
                    mask_area_pixels = np.sum(mask_binary) # zählt alle weißen Pixel in der Binärmaske
                    
                    # Berechnet wie gut die SAM-Maske mit der ursprünglichen BBox überlappt
                    bbox_mask = np.zeros((image.height, image.width), dtype=np.uint8)
                    bbox_mask[y1:y2, x1:x2] = 1
                    overlap = np.sum(mask_binary & bbox_mask)
                    bbox_overlap_ratio = overlap / np.sum(bbox_mask) if np.sum(bbox_mask) > 0 else 0
                    
                    # Schwerpunkt
                    y_coords, x_coords = np.where(mask_binary > 0)
                    if len(y_coords) > 0:
                        centroid_y = np.mean(y_coords)
                        centroid_x = np.mean(x_coords)
                        centroid_distance = np.sqrt((centroid_x - bbox_center[0])**2 + 
                                                    (centroid_y - bbox_center[1])**2)
                        normalized_distance = centroid_distance / max(image.width, image.height)
                    else:
                        normalized_distance = 1.0
                    
                    # Flächen-Ratio
                    area_ratio = mask_area_pixels / bbox_area
                    area_score = 1.0 - min(abs(area_ratio - 1.0), 1.0)
                    
                    # FOCUS_CHANGE spezifischer Score
                    score = (
                        bbox_overlap_ratio * 0.4 +      # 40% BBox-Überlappung
                        (1.0 - normalized_distance) * 0.25 +  # 25% Zentrumsnähe
                        area_score * 0.25 +             # 25% Flächenpassung
                        mask_max * 0.1                  # 10% SAM-Konfidenz
                    )
                    
                    print(f"   Maske {i+1}: Score={score:.3f}, "
                          f"Überlappung={bbox_overlap_ratio:.3f}, "
                          f"Fläche={mask_area_pixels:,}px")
                    
                    if score > best_score:
                        best_score = score
                        best_mask_idx = i
                
                print(f"✅ Beste Maske: Nr. {best_mask_idx+1} mit Score {best_score:.3f}")
                
                best_mask_original = all_masks[best_mask_idx]        
                
                mask_np = best_mask_original
                print(f"   ✅ Beste Maske in Originalgröße: {image.width}×{image.height}")
                
                # ============================================================
                # DYNAMISCHER THRESHOLD 
                # SAM gibt nur Wahrscheinlichkeiten aus!
                # Nachdem das Modell eine Maske für eine Person vorhersagt (wo jeder Pixel einen Wert zwischen 0 und 1 hat, 
                # wie "wahrscheinlich gehört dieser Pixel zur Person"), wird diese Maske binarisiert (0 oder 1), indem alle 
                # Pixel unter 0.05 auf 0 gesetzt werden, alle darüber auf 1.
                # ============================================================
                mask_max = mask_np.max() #höchster Wahrscheinlichkeitswert in SAM-Maske
                if best_score < 0.6:  # Schlechte Maskenqualität
                    dynamic_threshold = 0.15 # SEHR NIEDRIG für maximale Abdeckung
                    print(f"   ⚠️  Masken-Score niedrig ({best_score:.3f}). "
                          f"Threshold=0.15 für bessere Präzision")
                elif best_score < 0.8:
                    dynamic_threshold = max(0.25, mask_max * 0.5)  # Vorher 0.15/0.3 - JETZT 0.25/0.5
                    print(f"   ℹ️  Mittlere Maskenqualität. Threshold={dynamic_threshold:.3f}")                   
                else:
                    dynamic_threshold = max(0.35, mask_max * 0.7)  # sehr hoher Threshold für gute Masken
                    print(f"   ✅ Excellente Maske. Threshold={dynamic_threshold:.3f}")
                
                # Binärmaske erstellen
                mask_array = (mask_np > dynamic_threshold).astype(np.uint8) * 255

                # Fallback bei leerer Maske, der höchste Wert ist 0 also schwarz
                if mask_array.max() == 0:
                    print("   ⚠️  Maske leer, erstelle rechteckige Fallback-Maske")
                    mask_array = np.zeros((image.height, image.width), dtype=np.uint8)
                    # BBox auf 512x512 skalieren für Fallback
                    cv2.rectangle(mask_array, (x1, y1), (x2, y2), 255, -1) #weiße Box
                  

                # Damit wird die Rohmaske für die UI-Anzeige gespeichert
                raw_mask_array = mask_array.copy()

                print(f"🔧 FOCUS_CHANGE POSTPROCESSING (auf {image.width}×{image.height})")

                ###################################################
                #           POSTPROCESSING (Originalgröße)
                ###################################################
                print("🔧 FOCUS_CHANGE POSTPROCESSING (Originalgröße)")
                print(f"   mask_array - Min/Max: {mask_array.min()}/{mask_array.max()}")
                print(f"   mask_array - Weiße Pixel: {np.sum(mask_array > 0)}")
                print(f"   mask_array - Shape: {mask_array.shape}")
                print(f"   mask_array - dtype: {mask_array.dtype}")
                
                # 1. Findet und behält nur die größte zusammenhängende Komponente der Maske
                labeled_array, num_features = ndimage.label(mask_array)
                if num_features > 1:
                    sizes = ndimage.sum(mask_array, labeled_array, range(1, num_features + 1))
                    largest_component = np.argmax(sizes) + 1
                    mask_array = np.where(labeled_array == largest_component, mask_array, 0)
                    print(f"   ✅ Größte Komponente behalten ({num_features}→1)")
                
                # 2. Morphologische Operationen
                kernel_close = np.ones((5, 5), np.uint8)
                mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_CLOSE, kernel_close, iterations=2)
                
                # Für jeweils einen anderen Dilate-Wert für Inpaint und Composition
                clean_mask = mask_array.copy() 

                # 1. FÜR INPAINT: 5×5 Dilate auf clean_mask auf 3x3 herunter da Rahmen von SAM-Maske bei 512x512 zu sehen
                inpaint_binary_mask = cv2.dilate(clean_mask, np.ones((3,3), np.uint8), 1)

                print(f"🔳 [FOCUS] Inpainting-Maske gespeichert: {np.unique(inpaint_binary_mask)}")


                # 2. FÜR COMPOSITING: 15×15 Dilate + Blur AUF mask_array (nach close)
                kernel_dilate = np.ones((15, 15), np.uint8)
                mask_array = cv2.dilate(mask_array, kernel_dilate, iterations=1)               
             
                
                # 3. Weiche Übergänge mittlerer Blur für natürliche Übergänge bei Composition
                mask_array = cv2.GaussianBlur(mask_array, (9, 9), 2.0)
                
                # 4. Gamma-Korrektur
                mask_array_float = mask_array.astype(np.float32) / 255.0
                mask_array_float = np.clip(mask_array_float, 0.0, 1.0)
                mask_array_float = mask_array_float ** 0.85
                mask_array = (mask_array_float * 255).astype(np.uint8)
                
                # Konvertierung von NumPy-Array auf PIL-Image
                mask_original = Image.fromarray(mask_array).convert("L")
                raw_mask = Image.fromarray(raw_mask_array).convert("L")
                inpaint_binary_pil = Image.fromarray(inpaint_binary_mask).convert("L")  
                
                # Finale Maske für ControlNet
                mask = mask_original
                
                print(f"✅ FOCUS_CHANGE Maske erstellt: {mask.size}")
                return mask, raw_mask, inpaint_binary_pil
                
                #Wichtig: mask (SAM-Maske) muß in Originalgröße zurück sonst Probleme in Funktion scaled_image_and_mask_together
                #Und raw_mask auch in Originalgröße sonst Anzeige-Problem UI, inpaint_binary_pil auch in Originalgröße da
                #die Maske auch über die Funktion scaled_image_and_mask_together für Inpaint herunterskaliert wird.
                
                
            # ============================================================
            # BLOCK 3: FACE_ONLY_CHANGE
            # ============================================================
            elif mode == "face_only_change":
                print("-" * 60)
                print("👤 SPEZIALMODUS: NUR GESICHT - ROBUSTER WORKFLOW")
                print("-" * 60)
        
                # ============================================================
                # Originalbild sichern
                # Andere Vorgehensweise da SAM bei kleinen Köpfen sonst keine Chance hat!
                # Bild ausschneiden auf eine vergrößerte quadratische Box - Crops
                # ============================================================
                original_image = image
                print(f"💾 Originalbild gesichert: {original_image.size}")
                original_bbox = (x1, y1, x2, y2)  
                print(f"💾 Original-BBox gespeichert: {original_bbox}")


                #512x512-Bilder ohne Crop für mehr Kontext für SAM
                use_crop_strategy = True    #Flag

                if original_image.width <= 512 and original_image.height <= 512:
                    print("Bild ist 512x512 oder kleiner, verwende Originalgröße für SAM")
                    print(f"   Originalgröße: {original_image.width}×{original_image.height}")
                    
                    use_crop_strategy = False
                else:
                    print(f"📏 Bild ist größer als 512x512 ({original_image.size}) → Verwende Crop-Strategie")                  
                    use_crop_strategy = True
                    
        
                if use_crop_strategy:    
                    
                    # ============================================================
                    # Crop = BBox × 2.5 (ERHÖHT für mehr Kontext) 
                    # ============================================================
                    print("✂️ SCHRITT 2: ERSTELLE QUADRATISCHEN AUSSCHNITT (BBox × 2.5)")
        
                    # BBox-Zentrum berechnen
                    bbox_center_x = (x1 + x2) // 2
                    bbox_center_y = (y1 + y2) // 2
                    print(f"   📍 BBox-Zentrum: ({bbox_center_x}, {bbox_center_y})")
        
                    # Größte Dimension der BBox finden
                    bbox_width = x2 - x1
                    bbox_height = y2 - y1
                    bbox_max_dim = max(bbox_width, bbox_height)
                    print(f"   📏 BBox Dimensionen: {bbox_width} × {bbox_height} px")
                    print(f"   📐 Maximale BBox-Dimension: {bbox_max_dim} px")
        
                    # Crop-Größe berechnen (BBox × 2.5)
                    crop_size = int(bbox_max_dim * 2.5)
                    print(f"   🎯 Ziel-Crop-Größe: {crop_size} × {crop_size} px (BBox × 2.5)")
        
                    # Crop-Koordinaten berechnen (zentriert um BBox)
                    crop_x1 = bbox_center_x - crop_size // 2
                    crop_y1 = bbox_center_y - crop_size // 2
                    crop_x2 = crop_x1 + crop_size
                    crop_y2 = crop_y1 + crop_size
        
                    # Sicherstellen, dass Crop innerhalb der Bildgrenzen bleibt
                    crop_x1 = max(0, crop_x1)
                    crop_y1 = max(0, crop_y1)
                    crop_x2 = min(original_image.width, crop_x2)
                    crop_y2 = min(original_image.height, crop_y2)


                    # ITERATIVE ANPASSUNG für bessere Crop-Größe
                    max_iterations = 3
                    print(f"   🔄 Iterative Crop-Anpassung (max. {max_iterations} Versuche)")

                    for iteration in range(max_iterations):
                        actual_crop_width = crop_x2 - crop_x1
                        actual_crop_height = crop_y2 - crop_y1
                    
                        # Prüfen ob Crop groß genug ist
                        if actual_crop_width >= crop_size and actual_crop_height >= crop_size:
                            print(f"   ✅ Crop-Größe OK nach {iteration} Iteration(en): {actual_crop_width}×{actual_crop_height} px")
                            break
                    
                        print(f"   🔄 Iteration {iteration+1}: Crop zu klein ({actual_crop_width}×{actual_crop_height})")
                    
                        # BREITE anpassen (falls nötig)
                        if actual_crop_width < crop_size:
                            if crop_x1 == 0:  # Am linken Rand
                                crop_x2 = min(original_image.width, crop_x1 + crop_size)
                                print(f"     ← Breite angepasst (linker Rand): crop_x2 = {crop_x2}")
                            elif crop_x2 == original_image.width:  # Am rechten Rand
                                crop_x1 = max(0, crop_x2 - crop_size)
                                print(f"     → Breite angepasst (rechter Rand): crop_x1 = {crop_x1}")
                            else:
                                # Nicht am Rand - zentriert erweitern
                                missing_width = crop_size - actual_crop_width
                                expand_left = missing_width // 2
                                expand_right = missing_width - expand_left
                            
                                crop_x1 = max(0, crop_x1 - expand_left)
                                crop_x2 = min(original_image.width, crop_x2 + expand_right)
                                print(f"     ↔ Zentriert erweitert um {missing_width}px")
                    
                        # HÖHE anpassen (falls nötig)
                        if actual_crop_height < crop_size:
                            if crop_y1 == 0:  # Am oberen Rand
                                crop_y2 = min(original_image.height, crop_y1 + crop_size)
                                print(f"     ↑ Höhe angepasst (oberer Rand): crop_y2 = {crop_y2}")
                            elif crop_y2 == original_image.height:  # Am unteren Rand
                                crop_y1 = max(0, crop_y2 - crop_size)
                                print(f"     ↓ Höhe angepasst (unterer Rand): crop_y1 = {crop_y1}")
                            else:
                                # Nicht am Rand - zentriert erweitern
                                missing_height = crop_size - actual_crop_height
                                expand_top = missing_height // 2
                                expand_bottom = missing_height - expand_top
                            
                                crop_y1 = max(0, crop_y1 - expand_top)
                                crop_y2 = min(original_image.height, crop_y2 + expand_bottom)
                                print(f"     ↕ Zentriert erweitert um {missing_height}px")
                    
                        # Sicherstellen, dass innerhalb der Bildgrenzen
                        crop_x1 = max(0, crop_x1)
                        crop_y1 = max(0, crop_y1)
                        crop_x2 = min(original_image.width, crop_x2)
                        crop_y2 = min(original_image.height, crop_y2)
                    
                        # Letzte Iteration erreicht?
                        if iteration == max_iterations - 1:
                            actual_crop_width = crop_x2 - crop_x1
                            actual_crop_height = crop_y2 - crop_y1
                            print(f"   ⚠️  Max. Iterationen erreicht. Finaler Crop: {actual_crop_width}×{actual_crop_height} px")
                        
                            # Warnung wenn immer noch zu klein
                            if actual_crop_width < crop_size or actual_crop_height < crop_size:
                                min_acceptable = int(bbox_max_dim * 1.8)  # Mindestens 1.8× BBox
                                if actual_crop_width < min_acceptable or actual_crop_height < min_acceptable:
                                    print(f"   🚨 KRITISCH: Crop immer noch zu klein ({actual_crop_width}×{actual_crop_height})")
                                    print(f"   🚨 SAM könnte Probleme haben!")

                    print(f"   🔲 Finaler Crop-Bereich: [{crop_x1}, {crop_y1}, {crop_x2}, {crop_y2}]")
                    print(f"   📏 Finale Crop-Größe: {crop_x2-crop_x1} × {crop_y2-crop_y1} px")

        
                    # Bild ausschneiden- mit besten verfügbaren Crop der nach 3 Iterationen berechnet wurde
                    cropped_image = original_image.crop((crop_x1, crop_y1, crop_x2, crop_y2))
                    print(f"   ✅ Quadratischer Ausschnitt erstellt: {cropped_image.size}")
        
                    # ============================================================
                    # BBox-Koordinaten transformieren wegen neuer Koordinatenausrichtung (anderer Nullpunkt)
                    # ============================================================
                    print("📐 SCHRITT 3: BBox-KOORDINATEN TRANSFORMIEREN")
                    rel_x1 = x1 - crop_x1
                    rel_y1 = y1 - crop_y1
                    rel_x2 = x2 - crop_x1
                    rel_y2 = y2 - crop_y1
        
                    # Sicherstellen, dass BBox innerhalb des Crops liegt
                    rel_x1 = max(0, rel_x1)
                    rel_y1 = max(0, rel_y1)
                    rel_x2 = min(cropped_image.width, rel_x2)
                    rel_y2 = min(cropped_image.height, rel_y2)
        
                    print(f"   🎯 Relative BBox im Crop: [{rel_x1}, {rel_y1}, {rel_x2}, {rel_y2}]")
                    print(f"   📏 Relative BBox Größe: {rel_x2-rel_x1} × {rel_y2-rel_y1} px")
        
                    # ============================================================
                    # INTENSIVE BILDAUFBEREITUNG FÜR GESICHTSERKENNUNG
                    # ============================================================
                    print("🔍 SCHRITT 4: ERWEITERTE BILDAUFBEREITUNG FÜR GESICHTSERKENNUNG")
        
                    # 1. Kontrast verstärken
                    contrast_enhancer = ImageEnhance.Contrast(cropped_image)
                    enhanced_image = contrast_enhancer.enhance(1.3)  # 30% mehr Kontrast
        
                    # 2. Schärfe erhöhen für bessere Kantenerkennung
                    sharpness_enhancer = ImageEnhance.Sharpness(enhanced_image)
                    enhanced_image = sharpness_enhancer.enhance (1.4) # 40% mehr Schärfe
        
                    # 3. Helligkeit anpassen
                    brightness_enhancer = ImageEnhance.Brightness(enhanced_image)
                    enhanced_image = brightness_enhancer.enhance(1.05)  # 5% heller
        
                    print(f"   ✅ Erweiterte Bildaufbereitung abgeschlossen")
                    print(f"     • Kontrast: +30%")
                    print(f"     • Schärfe: +40%")
                    print(f"     • Helligkeit: +5%")
        
                    # Für SAM: Verwende aufbereitetes Crop-Bild und transformierte BBox-Koordinaten
                    image = enhanced_image
                    x1, y1, x2, y2 = rel_x1, rel_y1, rel_x2, rel_y2
        
                    print("   🔄 SAM wird auf aufbereitetem Ausschnitt ausgeführt")
                    print(f"   📊 SAM-Eingabegröße: {image.size}")


                else: #use_crop_strategy=False (Bild <=512)           
                    print("🎯 SCHRITT 2: VERWENDE ORIGINALBILD UND ORIGINAL-BBOX FÜR SAM")
                    print(f"   Originalbild-Größe: {original_image.size}")
                    print(f"   Original-BBox: [{x1}, {y1}, {x2}, {y2}]")
                    
                    # Keine Bildverbesserung für 512x512 - Original verwenden
                    image = original_image
                    #x1, y1, x2, y2 bleiben Originalkoordinaten sind zu Beginn des Blockes gespeichert

                ##########################################################
                #BBox-Berechnung für Heuristik immer Oroginal-BBox
                ##########################################################

                if use_crop_strategy:
                                    
                    bbox_x1, bbox_y1, bbox_x2, bbox_y2 = rel_x1, rel_y1, rel_x2, rel_y2
    
                    print(f"   🎯 Heuristik-BBox im Crop: [{bbox_x1}, {bbox_y1}, {bbox_x2}, {bbox_y2}]")
                                       
                else:
                    # Für Original: Direkt Original-BBox verwenden
                    bbox_x1, bbox_y1, bbox_x2, bbox_y2 = original_bbox

                    
                #########das folgende ist für beide Fälle####################
                # Heuristik-Parameter berechnen (konsistent für beide Fälle)
                bbox_width = bbox_x2 - bbox_x1
                bbox_height = bbox_y2 - bbox_y1
                bbox_area = bbox_width * bbox_height
                bbox_center = ((bbox_x1 + bbox_x2) // 2, (bbox_y1 + bbox_y2) // 2)
    
                print(f"📏 HEURISTIK-BBOX: [{bbox_x1}, {bbox_y1}, {bbox_x2}, {bbox_y2}]")
                print(f"📐 HEURISTIK-BBOX-Größe: {bbox_width}×{bbox_height}px = {bbox_area:,}px²")
                print(f"📍 HEURISTIK-BBOX-Zentrum: {bbox_center}")                  
                print(f"   ✅ SAM verwendet Original-BBox-Koordinaten")
               

                # ============================================================
                # SAM-AUSFÜHRUNG mit transformierter BBox und aufbereiteten Crop-Bild für Bild >512 oder
                # SAM-AUSFÜHRUNG mit Originalbild und Original-BBox für Bilder <=512
                # ============================================================

                print("-" * 60)
                print(f"📦 BOUNDING BOX DETAILS FÜR SAM:")               
                # Vorbereitung für SAM2 - WICHTIG: NUR EINE BBOX
                print("-" * 60)
                print("🖼️  BILDAUFBEREITUNG FÜR SAM 2")
                # SAM erwartet NumPy-Array, kein PIL
                image_np = np.array(image.convert("RGB"))
                
                # SAM bekommt die aktuelle BBox entweder Original oder transformiert
                input_boxes = [[[x1, y1, x2, y2]]]

                # Punkt in der BBox-Mitte (zur Ünterstützung von SAM damit BBox nicht zu dicht um Kopf gezogen werden muß!)
                center_x = (x1 + x2) // 2
                center_y = (y1 + y2) // 2

                # Punkt im Gesicht (30% höher vom Mittelpunkt)(auch für größere BBox)
                #bbox_height = y2 - y1
                #face_offset = int(bbox_height * 0.3)
                #face_x = center_x
                #face_y = center_y - face_offset
                #face_y = max(y1 + 10, min(face_y, y2 - 10))  # In BBox halten


                if is_back_head:
                    # 🔥 HINTERKOPF: ZWEI Punkte
                    back_offset = int(bbox_height * 0.4)
                    back_x = center_x
                    back_y = center_y + back_offset
                    back_y = min(back_y, y2 - 10)
    
                    input_points = [[[[center_x,center_y], [back_x, back_y]]]]
                    input_labels = [[[1, 0]]]
    
                    print(f"   🎯 HINTERKOPF-SAM: Positiv ({center_x},{center_y}), Negativ ({back_x},{back_y})")
                else:
                    # 😊 GESICHT: NUR EIN positiver Punkt
                    input_points = [[[[center_x, center_y]]]]
                    input_labels = [[[1]]]
    
                    print(f"   🎯 GESICHTS-SAM: Punkt ({center_x},{center_y})")
    
 
                # Aufruf des SAM-Prozessors mit den Variablen. Der Processor verpackt diese Rohdaten 
                # in die für das SAM-Modell erforderlichen Tensoren und speichert sie in inputs.
                inputs = self.sam_processor(
                    image_np, 
                    input_boxes=input_boxes,
                    input_points=input_points,    # Ein Punkt oder bei Hinterkopf 2
                    input_labels=input_labels,    # Ein Label oder bei Hinterkopf 2 
                    return_tensors="pt"
                ).to(self.device)                 # Ohne .to(self.device) werden die Tensoren standardmäßig im CPU-RAM erzeugt und gespeichert! Da GPU-Fehler!

                print(f"✅ Processor-Ausgabe: Dictionary mit {len(inputs)} Schlüsseln: {list(inputs.keys())}")
                print(f"   - 'pixel_values' Shape: {inputs['pixel_values'].shape}")
                print(f"   - 'input_boxes' Shape: {inputs['input_boxes'].shape}")
                if 'input_points' in inputs:
                    print(f"   - 'input_points' Shape: {inputs['input_points'].shape}")

                # 4. SAM2 Vorhersage
                print("-" * 60)
                print("🧠 SAM 2 INFERENZ (Vorhersage)")
                with torch.no_grad():
                    print("   Führe Vorhersage durch...")
                    outputs = self.sam_model(**inputs)
                    print(f"✅ Vorhersage abgeschlossen")
                    print(f"   Anzahl der Vorhersagemasken: {outputs.pred_masks.shape[2]}")
                
                # 5. Maske extrahieren
                print("📏 SCHRITT 6: MASKE EXTRAHIEREN")
                
                num_masks = outputs.pred_masks.shape[2]
                print(f"   SAM lieferte {num_masks} verschiedene Masken")   
                
                # Masken speichern in Array
                all_masks_crop = []        #Weiterverarbeitung in Crop-Größe oder Bildgröße <= 512

                
                for i in range(num_masks):
                    single_mask = outputs.pred_masks[:, :, i, :, :]
                    # 2. FÜR VERARBEITUNG: Auf CROP-GRÖSSE interpolieren
                    resized_mask_crop = F.interpolate(
                        single_mask,
                        size=(image.height, image.width),  # CROP-Größe bei Crop-Eingang sonst <= 512er-Größe
                        mode='bilinear',
                        align_corners=False
                    ).squeeze()
                    
                    mask_np = resized_mask_crop.sigmoid().cpu().numpy()
                    all_masks_crop.append(mask_np)


                    # Debug-Info
                    mask_binary = (mask_np > 0.5).astype(np.uint8)
                    print(f"   Maske {i+1}: {np.sum(mask_binary):,}px (Crop-Größe)") 
                     
            
                # ============================================================
                # HEURISTIK (zur Bestimmung der besten Maske) bei Bild>512 wird die beste Maske auf Crop-Größe ermittelt bei Bild<=512 auf Originalgröße
                # Es wird die Maske mit dem besten Score gewählt (und nicht mehr, wie vorher die Maske mit der größten Fläche!)
                # ============================================================
                print("🤔 HEURISTIK BERECHNEN")

                      
                # Heuristik-BBox für alle weiteren Berechnungen verwenden
                # (bbox_center und bbox_area sind korrekt für beide Fälle)              
                
                best_mask_idx = 0                    
                best_score = -1
                
                for i, mask_np in enumerate(all_masks_crop):
                    mask_max = mask_np.max()
                    
                    # Grundlegende Filterung
                    if mask_max < 0.3:
                        print(f"   ❌ Maske {i+1}: Zu niedrige Konfidenz ({mask_max:.3f}), überspringe")
                        continue
                    
                    # Adaptiver Threshold
                    adaptive_threshold = max(0.3, mask_max * 0.7)
                    mask_binary = (mask_np > adaptive_threshold).astype(np.uint8)
                    
                    if np.sum(mask_binary) == 0:
                        print(f"   ❌ Maske {i+1}: Keine Pixel nach Threshold {adaptive_threshold:.3f}")
                        continue
                        
                    #Maskenfläche in Pixeln
                    mask_area_pixels = np.sum(mask_binary) 

                    # ============================================================
                    #        SPEZIALHEURISTIK 
                    # ============================================================

                    print(f"   🔍 Analysiere Maske {i+1} auf {'Crop-' if use_crop_strategy else 'Original-'}Größe")
        
                    # 1. FLÄCHENBASIERTE BEWERTUNG (40%)
                    area_ratio = mask_area_pixels / bbox_area if bbox_area > 0 else 0
                    print(f"     📐 Flächen-Ratio: {area_ratio:.3f} ({mask_area_pixels:,} / {bbox_area:,} Pixel)")

                    
                    optimal_min, optimal_max = 0.8, 1.2
                    if optimal_min <= area_ratio <= optimal_max:
                        area_score = 1.0
                    elif area_ratio < optimal_min:
                        area_score = area_ratio / optimal_min
                    else:
                        area_score = optimal_max / area_ratio  # Starke Bestrafung für zu groß


                    # 2. BBOX-ÜBERLAPPUNG (wie gut überlappt die SAM-Maske die BBox)
                    bbox_mask = np.zeros((image.height, image.width), dtype=np.uint8)
                    bbox_mask[bbox_y1:bbox_y2, bbox_x1:bbox_x2] = 1
                    overlap = np.sum(mask_binary & bbox_mask)
                    bbox_overlap_ratio = overlap / bbox_area if bbox_area > 0 else 0  # WICHTIG: durch bbox_area!
        
                        
        
                    # 2. KOMPAKTHEIT/SOLIDITÄT (30%)
                    labeled_mask = measure.label(mask_binary)
                    regions = measure.regionprops(labeled_mask)
        
                    if len(regions) == 0:
                        compactness_score = 0.1
                        print(f"     ❌ Keine zusammenhängenden Regionen gefunden")
                    else:
                        # Größte Region finden (sollte der Kopf sein)
                        largest_region = max(regions, key=lambda r: r.area)
            
                        # Solidität = Fläche / konvexe Hüllenfläche
                        solidity = largest_region.solidity if hasattr(largest_region, 'solidity') else 0.7
            
                        # Exzentrizität (wie elliptisch) - Köpfe sind tendenziell elliptisch
                        eccentricity = largest_region.eccentricity if hasattr(largest_region, 'eccentricity') else 0.5
            
                        # Perfekt runde Formen (Kreis) sind 0, Linie wäre 1
                        # Köpfe haben typischerweise 0.5-0.8
                        if 0.4 <= eccentricity <= 0.9:
                            eccentricity_score = 1.0 - abs(eccentricity - 0.65) * 2
                        else:
                            eccentricity_score = 0.2
            
                        compactness_score = (solidity * 0.6 + eccentricity_score * 0.4)
                        print(f"     🎯 Kompaktheits-Analyse:")
                        print(f"       • Solidität (Fläche/Konvex): {solidity:.3f}")
                        print(f"       • Exzentrizität (Form): {eccentricity:.3f}")
                        print(f"       • Kompaktheits-Score: {compactness_score:.3f}")

                        
        
                    confidence_score = mask_max
                       
                    score = (
                        bbox_overlap_ratio * 0.65 +      # 50% BBox-Überlappung (vorher 20%, 65%)
                        compactness_score * 0.20 +       # 30% Kompaktheit (vorher 30%)
                        area_score * 0.10 +             # 15% Flächenpassung (vorher 40%)
                        confidence_score * 0.05         # 5% Konfidenz (vorher 10%)
                    )
        
                    print(f"     📊 GESICHTS-SCORES für Maske {i+1}:")
                    print(f"       • BBox-Überlappung: {bbox_overlap_ratio:.1%}")
                    print(f"       • Flächen-Score: {area_score:.3f}")
                    print(f"       • Kompaktheits-Score: {compactness_score:.3f}")
                    print(f"       • Konfidenz-Score: {confidence_score:.3f}")
                    print(f"       • GESAMTSCORE: {score:.3f}")

                    if score > best_score:
                        best_score = score
                        best_mask_idx = i
                        print(f"     🏆 Neue beste Maske: Nr. {i+1} mit Score {score:.3f}")

                print(f"✅ Beste Maske ausgewählt: Nr. {best_mask_idx+1} mit Score {best_score:.3f}")

                # Beste Maske verwenden
                mask_np = all_masks_crop[best_mask_idx]
                max_val = mask_np.max()
                print(f"🔍 Maximaler SAM-Konfidenzwert der besten Maske: {max_val:.3f}")
                

                # ============================================================
                # THRESHOLD-BESTIMMUNG Wahrscheinlichkeiten -> Binär (0,1)
                # ============================================================
                # Spezieller Threshold für Gesichter speziell Anime brauchen dickere Maske!
                # Aber auch allgemein für Kopf sind dicke Masken besser!
                if max_val < 0.5:
                    dynamic_threshold = 0.15 #anstatt 0.25
                    print(f"   ⚠️  SAM ist unsicher für Gesicht (max_val={max_val:.3f} < 0.5)")
                elif max_val < 0.8:
                    dynamic_threshold = max_val * 0.45  # anstatt 0.65 Mittlerer Threshold
                    print(f"   ℹ️  SAM ist mäßig sicher für Gesicht (max_val={max_val:.3f})")
                else:
                    dynamic_threshold = max_val * 0.55 # anstatt 0.75 Hoher Threshold
                    print(f"   ✅ SAM ist sicher für Gesicht (max_val={max_val:.3f} >= 0.8)")
        
                print(f"   🎯 Gesichts-Threshold: {dynamic_threshold:.3f}")

                # Binärmaske erstellen
                print("🐛 DEBUG THRESHOLD:")
                print(f"   mask_np Min/Max: {mask_np.min():.3f}/{mask_np.max():.3f}")
                print(f"   dynamic_threshold: {dynamic_threshold:.3f}")

                mask_array = (mask_np > dynamic_threshold).astype(np.uint8) * 255

                print(f"🚨 DEBUG BINÄRMASKE:")
                print(f"   mask_array Min/Max: {mask_array.min()}/{mask_array.max()}")
                print(f"   Weiße Pixel in mask_array: {np.sum(mask_array > 0)}")
                print(f"   Anteil weiße Pixel: {np.sum(mask_array > 0) / mask_array.size:.1%}")

                # Fallback wenn Maske leer
                if mask_array.max() == 0:
                    print("⚠️  KRITISCH: Binärmaske ist leer! Erzwinge Testmaske (BBox).")
                    print(f"   🚨 BBox für Fallback: x1={x1}, y1={y1}, x2={x2}, y2={y2}")
        
                    test_mask = np.zeros((image.height, image.width), dtype=np.uint8)
                    cv2.rectangle(test_mask, (x1, y1), (x2, y2), 255, -1)
        
                    mask_array = test_mask
                    print(f"🐛 DEBUG ERZWUNGENE MASKE: Weiße Pixel: {np.sum(mask_array > 0)}")

                # Rohmaske speichern
                raw_mask_array = mask_array.copy()

                # ============================================================
                #        POSTPROCESSING unterschiedlich für Crop/Original
                # ============================================================

                labeled_array, num_features = ndimage.label(mask_array)
                
                if num_features > 0:
                    # ERSTER SCHRITT: Nur Komponenten behalten, die in/nah der HEURISTIK-BBOX liegen
                    regions = measure.regionprops(labeled_array)
                    valid_regions = []
                    
                    for region in regions:
                        centroid_y, centroid_x = region.centroid
                        bbox_distance = np.sqrt((centroid_x - bbox_center[0])**2 + 
                                               (centroid_y - bbox_center[1])**2)
                        
                        # Maximaler Abstand: 50% der BBox-Diagonale
                        max_distance = np.sqrt(bbox_width**2 + bbox_height**2) * 0.5
                        
                        if bbox_distance <= max_distance:
                            valid_regions.append(region)
                    
                    if valid_regions:
                        # Größte valide Region finden
                        largest_region = max(valid_regions, key=lambda r: r.area)
                        mask_array = np.where(labeled_array == largest_region.label, mask_array, 0)
                        print(f"   ✅ {len(valid_regions)}/{num_features} Regionen in/nah BBox, größte behalten")
                    else:
                        print(f"   ⚠️  Keine Region in/nah BBox gefunden, alle behalten")
                
                # Binärmaske für Inpaint speichern (VOR weiteren Operationen!)
                inpaint_binary_mask = mask_array.copy()
              
                if use_crop_strategy:
                    print("👤 POSTPROCESSING AUF CROP-GRÖSSE")
        
                               
                    # MORPHOLOGISCHE OPERATIONEN FÜR SAUBEREN KOPF
                    print("   ⚙️  Morphologische Operationen für sauberen Kopf")
            
                        
                    # Zuerst CLOSE, um kleine Löcher im Kopf zu füllen
                    kernel_close = np.ones((7, 7), np.uint8)
                    mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_CLOSE, kernel_close, iterations=1)
                    print("     • MORPH_CLOSE (7x7) - Löcher im Kopf füllen")
            
                    # Dann OPEN, um kleine Ausreißer zu entfernen
                    kernel_open = np.ones((5, 5), np.uint8)
                    mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_OPEN, kernel_open, iterations=1)
                    print("     • MORPH_OPEN (5x5) - Rauschen entfernen")

                        
                    # LEICHTER DILATE FÜR MEHR ABDECKUNG (wichtig für Gesicht!)
                    print("   🔲 Leichter Dilate für natürliche Abdeckung")
                    kernel_dilate = np.ones((15, 15), np.uint8)  # Größerer Kernel für Gesicht
                    mask_array = cv2.dilate(mask_array, kernel_dilate, iterations=1)


                    #Speicherung der Binärmaske für Inpaint da keine Graupixel
                    inpaint_binary_mask = mask_array.copy()  # ← Bereinigt, aber scharfkantig
                    print(f"🔳 [FACE] Inpainting-Maske gespeichert: {np.unique(inpaint_binary_mask)}")
                    
                    
                    # WEICHER GAUSSIAN BLUR FÜR NATÜRLICHE ÜBERGÄNGE
                    print("   🔷 Gaussian Blur für weiche Hautübergänge (15x15, sigma=3.0)")
                    mask_array = cv2.GaussianBlur(mask_array, (15, 15), 3.0)

                    # GAMMA-KORREKTUR FÜR GLATTE, NATÜRLICHE KANTEN
                    print("   🎨 Gamma-Korrektur (0.7) für glatte Übergänge")
                    mask_array_float = mask_array.astype(np.float32) / 255.0
                    mask_array_float = np.clip(mask_array_float, 0.0, 1.0)
                    mask_array_float = mask_array_float ** 0.7  # Stärkeres Gamma für weichere Kanten
                    mask_array = (mask_array_float * 255).astype(np.uint8)

                    # NOCH EIN WEICHER BLUR FÜR EXTRA-GLÄTTE KANTEN
                    print("   💫 Finaler weicher Blur (9x9, sigma=1.5)")
                    mask_array = cv2.GaussianBlur(mask_array, (9, 9), 1.5)

                    # SICHERSTELLEN, DASS MASKE NICHT ZU DÜNN IST (speziell für Gesicht!)
                    print("   📏 Prüfe Maskendichte...")
                    white_pixels = np.sum(mask_array > 128)
                    bbox_area = (x2 - x1) * (y2 - y1)
                    coverage_ratio = white_pixels / bbox_area if bbox_area > 0 else 0

                    print(f"   📊 Aktuelle Abdeckung: {white_pixels:,}px / {bbox_area:,}px = {coverage_ratio:.1%}")

                    # Wenn Maske zu dünn (unter 90% der BBox), weiter erweitern
                    if coverage_ratio < 0.9:
                        print(f"   ⚠️  Maske zu dünn für Gesicht (<90%)")
                        print(f"   📈 Zusätzlicher Dilate...")
                        kernel_extra = np.ones((9, 9), np.uint8)
                        mask_array = cv2.dilate(mask_array, kernel_extra, iterations=1)
    
                        # Nochmal weichzeichnen
                        mask_array = cv2.GaussianBlur(mask_array, (11, 11), 2.0)

                    # ============================================================
                    # Maske und Rohmaske auf Originalgröße transformieren (nur für Crop)
                    # ============================================================
                    print("🔄 MASKE AUF ORIGINALGRÖSSE TRANSFORMIEREN")
                
                    # 1. Maske in Crop-Größe wird konveriert von NumPy nach PIL
                    mask_crop_pil = Image.fromarray(mask_array).convert("L")
    
                    # Leere Maske in Originalgröße
                    mask_original = Image.new("L", original_image.size, 0)
    
                    # Crop-Maske an richtiger Position in leerem Originalbild einfügen
                    # da Hauptprogramm Originalgröße erwartet.
                    mask_original.paste(mask_crop_pil, (crop_x1, crop_y1))
    
                    # 2. Rohmaske ebenfalls transformieren
                    raw_mask_crop_pil = Image.fromarray(raw_mask_array).convert("L")
                    raw_mask_original = Image.new("L", original_image.size, 0)
                    raw_mask_original.paste(raw_mask_crop_pil, (crop_x1, crop_y1))

                    #Binärmaske für Inpaint auf Originalgröße bringen
                    #konvertieren zu PIL-Image
                    inpaint_binary_crop_pil = Image.fromarray(inpaint_binary_mask).convert("L")
                    #Leeres schwarzes Bild in Originalgröße erstellen
                    inpaint_binary_original = Image.new("L", original_image.size, 0)
                    #Klebe Crop-SAM-Maske auf schwarzes Bild in Originalgröße
                    inpaint_binary_original.paste(inpaint_binary_crop_pil, (crop_x1, crop_y1))

                else: #keine use_crop_stategy Bild<=512
                    print("👤 POSTPROCESSING AUF ORIGINALGRÖSSE (≤512px)")
                           
                    # ANGEPASSTE Morphologische Operationen für Originalgröße
                    kernel_close = np.ones((5, 5), np.uint8)
                    mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_CLOSE, kernel_close, iterations=1)
                    print("     • MORPH_CLOSE (5x5) - Löcher im Kopf füllen")
            
                    kernel_open = np.ones((3, 3), np.uint8)
                    mask_array = cv2.morphologyEx(mask_array, cv2.MORPH_OPEN, kernel_open, iterations=1)
                    print("     • MORPH_OPEN (3x3) - Rauschen entfernen")

                    # Leichter Dilate für mehr Abdeckung
                    kernel_dilate = np.ones((9, 9), np.uint8)
                    mask_array = cv2.dilate(mask_array, kernel_dilate, iterations=1)
                    print("     • DILATE (3x3) - Natürliche Abdeckung")

                    # Binärmaske für Inpaint speichern (vor Blur)
                    inpaint_binary_mask = mask_array.copy()
                    
                    # ANGEPASSTER Gaussian Blur für Originalgröße
                    mask_array = cv2.GaussianBlur(mask_array, (11, 11), 2.0)
                    print("     • GAUSSIAN BLUR (11x11, sigma=2.0) - Weiche Übergänge")

                    # Gamma-Korrektur
                    mask_array_float = mask_array.astype(np.float32) / 255.0
                    mask_array_float = np.clip(mask_array_float, 0.0, 1.0)
                    mask_array_float = mask_array_float ** 0.8
                    mask_array = (mask_array_float * 255).astype(np.uint8)
                    print("     • GAMMA (0.8) - Glatte Übergänge")

                    # Finaler weicher Blur
                    mask_array = cv2.GaussianBlur(mask_array, (7, 7), 1.0)
                    print("     • FINALER BLUR (7x7, sigma=1.0)")

                    # Prüfe Maskendichte
                    white_pixels = np.sum(mask_array > 128)
                    coverage_ratio = white_pixels / bbox_area if bbox_area > 0 else 0
                    print(f"   📊 Aktuelle Abdeckung: {white_pixels:,}px / {bbox_area:,}px = {coverage_ratio:.1%}")

                    if coverage_ratio < 0.9:
                        print(f"   ⚠️  Maske zu dünn für Gesicht (<90%)")
                        kernel_extra = np.ones((5, 5), np.uint8)
                        mask_array = cv2.dilate(mask_array, kernel_extra, iterations=1)
                        mask_array = cv2.GaussianBlur(mask_array, (7, 7), 1.5)

                    # Masken sind bereits in Originalgröße
                    mask_original = Image.fromarray(mask_array).convert("L")
                    raw_mask_original = Image.fromarray(raw_mask_array).convert("L")
                    inpaint_binary_original = Image.fromarray(inpaint_binary_mask).convert("L")
          
                                       
                # ============================================================
                # ABSCHLIESSENDE STATISTIK
                # ============================================================
                print("📊 FINALE MASKEN-STATISTIK FÜR FEHLERANALYSE")

                # Berechnungen (bleiben gleich)
                final_white = np.sum(mask_array > 128)
                final_coverage = final_white / bbox_area if bbox_area > 0 else 0
                final_array = np.array(mask_original)
                white_pixels = np.sum(final_array > 0)
                total_pixels = final_array.size
                white_ratio = white_pixels / total_pixels * 100 if total_pixels > 0 else 0

                original_bbox_width = original_bbox[2] - original_bbox[0]
                original_bbox_height = original_bbox[3] - original_bbox[1]
                original_face_area = original_bbox_width * original_bbox_height
                coverage_ratio = white_pixels / original_face_area if original_face_area > 0 else 0

                # Fehlende Variablen für den else-Fall definieren
                if not use_crop_strategy:
                    crop_size = "N/A"  # not available
                    crop_x1 = crop_y1 = crop_x2 = crop_y2 = "N/A"

                # Strukturierte Ausgabe
                print(f"   🖼️  Bildgröße: {original_image.size[0]}×{original_image.size[1]} | "
                      f"Crop-Strategie: {'JA' if use_crop_strategy else 'NEIN'}")
                print(f"   📦 Original-BBox: {original_bbox} | "
                      f"Fläche: {original_face_area:,} px² ({original_bbox_width}×{original_bbox_height})")
                print(f"   🎯 SAM-Ergebnis: Beste Maske #{best_mask_idx+1} | Score: {best_score:.3f} | "
                      f"Konfidenz: {max_val:.3f} | Verfügbare Masken: {num_masks}")
                print(f"   👤 Gesichtsabdeckung: {coverage_ratio:.1%} der BBox "
                      f"({'OPTIMAL' if 0.8 <= coverage_ratio <= 1.2 else 'UNTER' if coverage_ratio < 0.7 else 'ÜBER'})")
                print(f"   📐 Maskenpixel: {white_pixels:,} weiß ({white_ratio:.1f}%) | "
                      f"{total_pixels-white_pixels:,} schwarz ({100-white_ratio:.1f}%)")
                print(f"   ⚙️  Postprocessing: {num_features} Komponenten → 1 behalten | "
                      f"Operationen: MORPH_CLOSE, MORPH_OPEN, DILATE, GAUSSIAN_BLUR, GAMMA")
                if use_crop_strategy:
                    print(f"   🔄 Crop-Größe: {crop_size}×{crop_size}px | "
                          f"Position: [{crop_x1},{crop_y1},{crop_x2},{crop_y2}]")
                    print(f"   📏 Crop-interne Abdeckung: {final_coverage:.1%} (technisch)")
                else:
                    print(f"   🔄 Direktverarbeitung auf Originalgröße")
                    print(f"   🎛️  Modus: {mode} | Threshold: {dynamic_threshold:.3f}")

                # Warnungen
                if coverage_ratio < 0.7:
                    print(f"   ⚠️  WARNUNG: Geringe Gesichtsabdeckung ({coverage_ratio:.1%})")
                elif coverage_ratio > 1.3:
                    print(f"   ⚠️  WARNUNG: Sehr hohe Gesichtsabdeckung ({coverage_ratio:.1%})")
                elif 0.8 <= coverage_ratio <= 1.2:
                    print(f"   ✅ OPTIMALE Gesichtsabdeckung ({coverage_ratio:.1%})")

                print("#" * 80)
                print(f"✅ SAM 2 SEGMENTIERUNG ABGESCHLOSSEN")
                print(f"📐 Finale Maskengröße: {mask_original.size}")
                print(f"🎛️  Verwendeter Modus: {mode}")

                if use_crop_strategy:
                    print(f"👤 Crop={crop_size}×{crop_size}px, Heuristik-Score={best_score:.3f}")
                else:
                    print(f"👤 Direktverarbeitung, Heuristik-Score={best_score:.3f}")
                    
                print(f"👤 Kopfabdeckung: {coverage_ratio:.1%} der BBox")
                print("#" * 80)

                         
                return mask_original, raw_mask_original, inpaint_binary_original

                #Maske, Raw_mask und Binärmaske in Originalgröße zurück!
                             
            # ============================================================
            # UNBEKANNTER MODUS
            # ============================================================
            else:
                print(f"❌ Unbekannter Modus: {mode}")
                return self._create_rectangular_mask(image, bbox_coords, "focus_change")
                
        except Exception as e:
            print("❌" * 40)
            print("❌ FEHLER IN SAM 2 SEGMENTIERUNG")
            print(f"Fehler: {str(e)[:200]}")
            print("❌" * 40)
            import traceback
            traceback.print_exc()
            
            # Fallback
            fallback_mask = self._create_rectangular_mask(original_image, original_bbox, mode)
            if fallback_mask.size != original_image.size:
                print(f"   ⚠️  Fallback-Maske angepasst: {fallback_mask.size}{original_image.size}")
                fallback_mask = fallback_mask.resize(original_image.size, Image.Resampling.NEAREST)
            
            return fallback_mask, fallback_mask


    def _create_rectangular_mask(self, image, bbox_coords, mode):
        """Fallback: Erstellt rechteckige Maske"""
        print("#" * 80)
        print("# ⚠️  FALLBACK: ERSTELLE RECHTECKIGE MASKE")
        print("#" * 80)
        
        from PIL import ImageDraw

        mask = Image.new("L", image.size, 0)
        print(f"📐 Erstelle leere Maske: {mask.size}")

        if bbox_coords and all(coord is not None for coord in bbox_coords):
            x1, y1, x2, y2 = self._validate_bbox(image, bbox_coords)
            draw = ImageDraw.Draw(mask)

            if mode == "environment_change":
                draw.rectangle([0, 0, image.size[0], image.size[1]], fill=255)
                draw.rectangle([x1, y1, x2, y2], fill=0)
                print(f"   Modus: Umgebung ändern - BBox geschützt: [{x1}, {y1}, {x2}, {y2}]")
            else:
                draw.rectangle([x1, y1, x2, y2], fill=255)
                print(f"   Modus: Focus/Gesicht ändern - BBox verändert: [{x1}, {y1}, {x2}, {y2}]")

        print("✅ Rechteckige Maske erstellt")
        return mask

    def load_pose_detector(self):
        """Lädt nur den Pose-Detector"""
        if self.pose_detector is None:
            print("#" * 80)
            print("# 📥 LADE POSE DETECTOR")
            print("#" * 80)
            try:
                self.pose_detector = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
                print("✅ Pose-Detector geladen")
            except Exception as e:
                print(f"⚠️ Pose-Detector konnte nicht geladen werden: {e}")
        return self.pose_detector

    def load_midas_model(self):
        """Lädt MiDaS Model für Depth Maps"""
        if self.midas_model is None:
            print("#" * 80)
            print("# 📥 LADE MIDAS MODELL FÜR DEPTH MAPS")
            print("#" * 80)
            try:
                import torchvision.transforms as T

                self.midas_model = torch.hub.load(
                    "intel-isl/MiDaS",
                    "DPT_Hybrid",
                    trust_repo=True
                )

                self.midas_model.to(self.device)
                self.midas_model.eval()

                self.midas_transform = T.Compose([
                    T.Resize(384),
                    T.ToTensor(),
                    T.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
                ])

                print("✅ MiDaS Modell erfolgreich geladen")
            except Exception as e:
                print(f"❌ MiDaS konnte nicht geladen werden: {e}")
                print("ℹ️ Verwende Fallback-Methode")
                self.midas_model = None

        return self.midas_model

    def extract_pose_simple(self, image):
        """Einfache Pose-Extraktion ohne komplexe Abhängigkeiten"""
        print("#" * 80)
        print("# ⚠️  ERSTELLE EINFACHE POSE-MAP (FALLBACK)")
        print("#" * 80)
        try:
            img_array = np.array(image.convert("RGB"))
            edges = cv2.Canny(img_array, 100, 200)
            pose_image = Image.fromarray(edges).convert("RGB")
            print("⚠️ Verwende Kanten-basierte Pose-Approximation")
            return pose_image
        except Exception as e:
            print(f"Fehler bei einfacher Pose-Extraktion: {e}")
            return image.convert("RGB").resize((512, 512))

    def extract_pose(self, image):
        """Extrahiert Pose-Map aus Bild mit Fallback"""
        print("#" * 80)
        print("# 🕺 ERSTELLE POSE-MAP")
        print("#" * 80)
        try:
            detector = self.load_pose_detector()
            if detector is None:
                print("⚠️ Kein Pose-Detector verfügbar, verwende Fallback")
                return self.extract_pose_simple(image)

            print("   Extrahiere Pose mit OpenPose und allen Gelenkpunkten")
            
            pose_image = detector(
                image, 
                include_body=True,
                include_hand=True,       # 🔥 Hände einschließen (21 Punkte pro Hand)
                include_face=True,       # 🔥 Gesicht einschließen (70 Punkte)
                hand_and_face=True,      # 🔥 Beide gleichzeitig
                include_foot=True,
                detect_resolution=896,    # 🔥 Höhere Detektionsauflösung für Details
                image_resolution=512,    # Ausgabegröße
                return_pil=True          
            )
            print("✅ Detaillierte Pose-Map erstellt")
            print(f"   🔥 137 Gelenkpunkte (statt nur 25)")
            print(f"   🔥 Enthält: Körper (25) + Hände (42) + Gesicht (70)")
            print(f"   🔥 Detektionsauflösung: 768px für mehr Details")

            return pose_image
        except Exception as e:
            print(f"Fehler bei Pose-Extraktion: {e}")
            return self.extract_pose_simple(image)

    def extract_canny_edges(self, image):
        """Extrahiert Canny Edges für Umgebungserhaltung"""
        print("#" * 80)
        print("# 🎨 ERSTELLE CANNY EDGE MAP")
        print("#" * 80)
        try:
            img_array = np.array(image.convert("RGB"))

            gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
            edges = cv2.Canny(gray, 100, 200)

            edges_rgb = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
            edges_image = Image.fromarray(edges_rgb)

            print("✅ Canny Edge Map erstellt")
            return edges_image
        except Exception as e:
            print(f"Fehler bei Canny Edge Extraction: {e}")
            return image.convert("RGB").resize((512, 512))

    def extract_depth_map(self, image):
        """
        Extrahiert Depth Map mit MiDaS (Fallback auf Filter)
        """
        print("#" * 80)
        print("# 🏔️  ERSTELLE DEPTH MAP")
        print("#" * 80)
        try:
            midas = self.load_midas_model()
            if midas is not None:
                print("🎯 Verwende MiDaS für Depth Map...")

                import torchvision.transforms as T

                img_transformed = self.midas_transform(image).unsqueeze(0).to(self.device)

                with torch.no_grad():
                    print("   Führe MiDaS Inferenz durch...")
                    prediction = midas(img_transformed)
                    prediction = torch.nn.functional.interpolate(
                        prediction.unsqueeze(1),
                        size=image.size[::-1],
                        mode="bicubic",
                        align_corners=False,
                    ).squeeze()

                depth_np = prediction.cpu().numpy()
                depth_min, depth_max = depth_np.min(), depth_np.max()
                print(f"   Tiefenwerte: Min={depth_min:.3f}, Max={depth_max:.3f}")

                if depth_max > depth_min:
                    depth_np = (depth_np - depth_min) / (depth_max - depth_min)

                depth_np = (depth_np * 255).astype(np.uint8)
                depth_image = Image.fromarray(depth_np).convert("RGB")

                print("✅ MiDaS Depth Map erfolgreich erstellt")
                return depth_image

            else:
                raise Exception("MiDaS nicht geladen")

        except Exception as e:
            print(f"⚠️ MiDaS Fehler: {e}. Verwende Fallback...")
            try:
                img_array = np.array(image.convert("RGB"))
                gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)

                depth_map = cv2.GaussianBlur(gray, (5, 5), 0)
                depth_rgb = cv2.cvtColor(depth_map, cv2.COLOR_GRAY2RGB)
                depth_image = Image.fromarray(depth_rgb)

                print("✅ Fallback Depth Map erstellt")
                return depth_image
            except Exception as fallback_error:
                print(f"❌ Auch Fallback fehlgeschlagen: {fallback_error}")
                return image.convert("RGB").resize((512, 512))

    def prepare_controlnet_maps(self, image, keep_environment=False):
        """
        ERSTELLT NUR CONDITIONING-MAPS, generiert KEIN Bild.
        """
        print("#" * 80)
        print("# 🎯 STARTE CONTROLNET CONDITIONING-MAP ERSTELLUNG")
        print("#" * 80)
        print(f"📐 Eingabebild-Größe: {image.size}")
        print(f"🎛️  Modus: {'Depth + Canny' if keep_environment else 'OpenPose + Canny'}")

        if keep_environment:
            print("   Modus: Depth + Canny")
            print("   Schritt 1/2: Extrahiere Depth Map...")
            depth_map = self.extract_depth_map(image)
            print("   Schritt 2/2: Extrahiere Canny Edges...")
            canny_map = self.extract_canny_edges(image)
            conditioning_images = [depth_map, canny_map]
            extra_maps = {"depth": depth_map, "canny": canny_map}  # NEU
        else:
            print("   Modus: OpenPose + Canny")
            print("   Schritt 1/2: Extrahiere Pose Map...")
            pose_map = self.extract_pose(image)
            print("   Schritt 2/2: Extrahiere Canny Edges...")
            canny_map = self.extract_canny_edges(image)
            conditioning_images = [pose_map, canny_map]
            extra_maps = {"pose": pose_map, "canny": canny_map}

        print("-" * 60)
        print(f"✅ {len(conditioning_images)} CONDITIONING-MAPS ERSTELLT")
        for i, img in enumerate(conditioning_images):
            print(f"   Map {i+1}: {img.size}, Modus: {img.mode}")
        print("#" * 80)
        
        return conditioning_images, extra_maps


# Globale Instanz
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if device == "cuda" else torch.float32
controlnet_processor = ControlNetProcessor(device=device, torch_dtype=torch_dtype)