File size: 36,024 Bytes
7b977a8
8320ccc
7b977a8
0bc7901
8320ccc
 
 
a9f1fc6
8320ccc
 
 
 
 
 
a96e8d6
8320ccc
 
 
 
 
 
 
 
 
 
 
7acaad7
8320ccc
 
 
3c77caa
187ccb9
9223079
7acaad7
0f3f5ca
8e76240
 
 
 
a96e8d6
8e76240
 
 
 
 
 
9705edb
7acaad7
 
3c77caa
0bc7901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8320ccc
 
 
0bc7901
 
 
 
 
 
 
 
 
7acaad7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c4807
7acaad7
9223079
9705edb
40c4807
 
 
 
 
 
 
 
 
 
 
 
 
 
9705edb
 
 
 
 
 
 
 
 
 
9223079
8320ccc
9223079
 
 
9705edb
 
 
 
 
 
 
 
 
 
9223079
8320ccc
9223079
 
9705edb
7b977a8
 
 
 
772e4c0
 
7b977a8
 
4d4dd90
7b977a8
772e4c0
7b977a8
 
772e4c0
 
 
7b977a8
 
772e4c0
 
 
 
 
 
 
4d4dd90
772e4c0
 
7b977a8
 
 
 
 
 
4d4dd90
 
7b977a8
 
49a0323
4d4dd90
b075789
4d4dd90
 
2eaeef9
4d4dd90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b075789
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d4dd90
772e4c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b977a8
772e4c0
4d4dd90
b075789
772e4c0
 
8e76240
 
 
 
 
 
 
7b977a8
772e4c0
 
7b977a8
 
 
 
 
 
 
 
42dde81
7b977a8
 
 
 
 
 
 
 
 
8d7004c
 
4d4dd90
 
8d7004c
 
 
 
 
c3f14e3
8d7004c
 
 
a96e8d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8320ccc
a96e8d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8320ccc
a96e8d6
 
7b977a8
9705edb
 
 
 
 
a96e8d6
 
9705edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d4dd90
 
 
7b977a8
 
 
 
 
 
 
 
 
8d7004c
7b977a8
8d7004c
7b977a8
8e76240
42dde81
8e76240
8d7004c
a96e8d6
 
 
 
 
 
 
7b977a8
a96e8d6
 
 
7b977a8
4d4dd90
 
4a7fc02
7b977a8
4a7fc02
 
a96e8d6
8d7004c
 
a96e8d6
 
 
 
7b977a8
 
 
5069bec
9705edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b977a8
4d4dd90
 
 
9705edb
7b977a8
 
 
 
 
 
 
8e76240
7b977a8
9705edb
a96e8d6
 
7b977a8
 
a96e8d6
 
 
 
 
7b977a8
a96e8d6
733c569
 
a96e8d6
 
7b977a8
 
a96e8d6
 
 
 
 
7b977a8
a96e8d6
 
733c569
 
a96e8d6
8869f68
 
 
 
 
a96e8d6
8869f68
 
 
 
8320ccc
 
 
7b977a8
 
 
 
 
9705edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a96e8d6
 
7b977a8
 
 
a96e8d6
 
 
 
7b977a8
260ecba
9705edb
7b977a8
a96e8d6
7b977a8
 
260ecba
 
 
 
 
a96e8d6
 
260ecba
7b977a8
 
 
 
 
 
 
e9f6961
7b977a8
 
 
 
5069bec
9705edb
 
 
 
e9f6961
9705edb
 
 
 
 
 
 
 
 
 
e9f6961
9705edb
7b977a8
 
 
 
 
 
a96e8d6
8320ccc
7b977a8
e9f6961
7b977a8
 
e9f6961
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b977a8
 
 
 
4a7fc02
d21720c
10dcc2e
4a7fc02
 
 
 
d21720c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7fc02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10dcc2e
 
e9f6961
10dcc2e
 
a96e8d6
10dcc2e
 
 
 
4a7fc02
e9f6961
68a65da
 
 
 
 
 
8320ccc
68a65da
10dcc2e
 
 
 
 
 
 
68a65da
10dcc2e
4a7fc02
 
7b977a8
9705edb
 
 
 
 
 
 
 
 
 
3c77caa
7acaad7
e400e91
9705edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c77caa
9705edb
 
 
 
 
 
 
 
 
 
 
7b977a8
 
d21720c
 
 
 
 
 
42dde81
 
 
 
7b977a8
6ae8c1a
8320ccc
6ae8c1a
 
 
 
e400e91
7b977a8
7acaad7
7b977a8
 
 
5069bec
0bc7901
e400e91
 
3c77caa
 
4c930ba
e400e91
 
4c930ba
187ccb9
3c77caa
7b977a8
 
8320ccc
7b977a8
 
 
 
7acaad7
7b977a8
 
 
5069bec
0bc7901
 
e400e91
 
 
 
3c77caa
 
4c930ba
e400e91
 
0bc7901
7b977a8
 
 
 
 
 
 
 
5808772
 
 
4c930ba
187ccb9
4d4dd90
 
42dde81
 
 
 
4d4dd90
42dde81
 
 
 
 
 
 
7b977a8
42dde81
 
 
 
 
 
 
 
a96e8d6
5808772
4c930ba
 
42dde81
 
 
 
 
 
 
4a7fc02
42dde81
5808772
4c930ba
42dde81
187ccb9
42dde81
e9f6961
7b977a8
 
a96e8d6
3c77caa
7b977a8
b7f7f2c
5808772
187ccb9
 
4a7fc02
 
 
e9f6961
68a65da
 
 
 
 
8320ccc
7b977a8
42dde81
 
 
 
4a7fc02
 
42dde81
7b977a8
 
 
 
 
c3f14e3
7b977a8
 
4a7fc02
68a65da
7b977a8
 
 
 
 
 
a96e8d6
 
 
 
 
 
 
 
 
7b977a8
4d4dd90
 
 
 
 
 
2eaeef9
 
 
 
 
 
 
b075789
2eaeef9
b075789
 
 
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
import os
import pickle
import random
import shutil
import time
import warnings
from itertools import combinations
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union

import cv2
import gradio as gr
import matplotlib.pyplot as plt
import numpy as np
import poselib
import psutil
from PIL import Image

from hloc import (
    DEVICE,
    extract_features,
    extractors,
    logger,
    match_dense,
    match_features,
    matchers,
)
from hloc.utils.base_model import dynamic_load

from .viz import display_keypoints, display_matches, fig2im, plot_images

warnings.simplefilter("ignore")

ROOT = Path(__file__).parent.parent
# some default values
DEFAULT_SETTING_THRESHOLD = 0.1
DEFAULT_SETTING_MAX_FEATURES = 2000
DEFAULT_DEFAULT_KEYPOINT_THRESHOLD = 0.01
DEFAULT_ENABLE_RANSAC = True
DEFAULT_RANSAC_METHOD = "CV2_USAC_MAGSAC"
DEFAULT_RANSAC_REPROJ_THRESHOLD = 8
DEFAULT_RANSAC_CONFIDENCE = 0.999
DEFAULT_RANSAC_MAX_ITER = 10000
DEFAULT_MIN_NUM_MATCHES = 4
DEFAULT_MATCHING_THRESHOLD = 0.2
DEFAULT_SETTING_GEOMETRY = "Homography"
GRADIO_VERSION = gr.__version__.split(".")[0]
MATCHER_ZOO = None


class ModelCache:
    def __init__(self, max_memory_size: int = 8):
        self.max_memory_size = max_memory_size
        self.current_memory_size = 0
        self.model_dict = {}
        self.model_timestamps = []

    def cache_model(self, model_key, model_loader_func, model_conf):
        if model_key in self.model_dict:
            self.model_timestamps.remove(model_key)
            self.model_timestamps.append(model_key)
            logger.info(f"Load cached {model_key}")
            return self.model_dict[model_key]

        model = self._load_model_from_disk(model_loader_func, model_conf)
        while self._calculate_model_memory() > self.max_memory_size:
            if len(self.model_timestamps) == 0:
                logger.warn(
                    "RAM: {}GB, MAX RAM: {}GB".format(
                        self._calculate_model_memory(), self.max_memory_size
                    )
                )
                break
            oldest_model_key = self.model_timestamps.pop(0)
            self.current_memory_size = self._calculate_model_memory()
            logger.info(f"Del cached {oldest_model_key}")
            del self.model_dict[oldest_model_key]

        self.model_dict[model_key] = model
        self.model_timestamps.append(model_key)

        self.print_memory_usage()
        logger.info(f"Total cached {list(self.model_dict.keys())}")

        return model

    def _load_model_from_disk(self, model_loader_func, model_conf):
        return model_loader_func(model_conf)

    def _calculate_model_memory(self, verbose=False):
        host_colocation = int(os.environ.get("HOST_COLOCATION", "1"))
        vm = psutil.virtual_memory()
        du = shutil.disk_usage(".")
        if verbose:
            logger.info(
                f"RAM: {vm.used / 1e9:.1f}/{vm.total / host_colocation / 1e9:.1f}GB"
            )
            logger.info(
                f"DISK: {du.used / 1e9:.1f}/{du.total / host_colocation / 1e9:.1f}GB"
            )
        return vm.used / 1e9

    def print_memory_usage(self):
        self._calculate_model_memory(verbose=True)


model_cache = ModelCache()


def load_config(config_name: str) -> Dict[str, Any]:
    """
    Load a YAML configuration file.

    Args:
        config_name: The path to the YAML configuration file.

    Returns:
        The configuration dictionary, with string keys and arbitrary values.
    """
    import yaml

    with open(config_name, "r") as stream:
        try:
            config: Dict[str, Any] = yaml.safe_load(stream)
        except yaml.YAMLError as exc:
            logger.error(exc)
    return config


def get_matcher_zoo(
    matcher_zoo: Dict[str, Dict[str, Union[str, bool]]]
) -> Dict[str, Dict[str, Union[Callable, bool]]]:
    """
    Restore matcher configurations from a dictionary.

    Args:
        matcher_zoo: A dictionary with the matcher configurations,
            where the configuration is a dictionary as loaded from a YAML file.

    Returns:
        A dictionary with the matcher configurations, where the configuration is
            a function or a function instead of a string.
    """
    matcher_zoo_restored = {}
    for k, v in matcher_zoo.items():
        matcher_zoo_restored[k] = parse_match_config(v)
    return matcher_zoo_restored


def parse_match_config(conf):
    if conf["dense"]:
        return {
            "matcher": match_dense.confs.get(conf["matcher"]),
            "dense": True,
        }
    else:
        return {
            "feature": extract_features.confs.get(conf["feature"]),
            "matcher": match_features.confs.get(conf["matcher"]),
            "dense": False,
        }


def get_model(match_conf: Dict[str, Any]):
    """
    Load a matcher model from the provided configuration.

    Args:
        match_conf: A dictionary containing the model configuration.

    Returns:
        A matcher model instance.
    """
    Model = dynamic_load(matchers, match_conf["model"]["name"])
    model = Model(match_conf["model"]).eval().to(DEVICE)
    return model


def get_feature_model(conf: Dict[str, Dict[str, Any]]):
    """
    Load a feature extraction model from the provided configuration.

    Args:
        conf: A dictionary containing the model configuration.

    Returns:
        A feature extraction model instance.
    """
    Model = dynamic_load(extractors, conf["model"]["name"])
    model = Model(conf["model"]).eval().to(DEVICE)
    return model


def gen_examples():
    random.seed(1)
    example_matchers = [
        "disk+lightglue",
        "xfeat(sparse)",
        "dedode",
        "loftr",
        "disk",
        "RoMa",
        "d2net",
        "aspanformer",
        "topicfm",
        "superpoint+superglue",
        "superpoint+lightglue",
        "superpoint+mnn",
        "disk",
    ]

    def distribute_elements(A, B):
        new_B = np.array(B, copy=True).flatten()
        np.random.shuffle(new_B)
        new_B = np.resize(new_B, len(A))
        np.random.shuffle(new_B)
        return new_B.tolist()

    # normal examples
    def gen_images_pairs(count: int = 5):
        path = str(ROOT / "datasets/sacre_coeur/mapping")
        imgs_list = [
            os.path.join(path, file)
            for file in os.listdir(path)
            if file.lower().endswith((".jpg", ".jpeg", ".png"))
        ]
        pairs = list(combinations(imgs_list, 2))
        if len(pairs) < count:
            count = len(pairs)
        selected = random.sample(range(len(pairs)), count)
        return [pairs[i] for i in selected]

    # rotated examples
    def gen_rot_image_pairs(count: int = 5):
        path = ROOT / "datasets/sacre_coeur/mapping"
        path_rot = ROOT / "datasets/sacre_coeur/mapping_rot"
        rot_list = [45, 180, 90, 225, 270]
        pairs = []
        for file in os.listdir(path):
            if file.lower().endswith((".jpg", ".jpeg", ".png")):
                for rot in rot_list:
                    file_rot = "{}_rot{}.jpg".format(Path(file).stem, rot)
                    if (path_rot / file_rot).exists():
                        pairs.append(
                            [
                                path / file,
                                path_rot / file_rot,
                            ]
                        )
        if len(pairs) < count:
            count = len(pairs)
        selected = random.sample(range(len(pairs)), count)
        return [pairs[i] for i in selected]

    def gen_scale_image_pairs(count: int = 5):
        path = ROOT / "datasets/sacre_coeur/mapping"
        path_scale = ROOT / "datasets/sacre_coeur/mapping_scale"
        scale_list = [0.3, 0.5]
        pairs = []
        for file in os.listdir(path):
            if file.lower().endswith((".jpg", ".jpeg", ".png")):
                for scale in scale_list:
                    file_scale = "{}_scale{}.jpg".format(Path(file).stem, scale)
                    if (path_scale / file_scale).exists():
                        pairs.append(
                            [
                                path / file,
                                path_scale / file_scale,
                            ]
                        )
        if len(pairs) < count:
            count = len(pairs)
        selected = random.sample(range(len(pairs)), count)
        return [pairs[i] for i in selected]

    # extramely hard examples
    def gen_image_pairs_wxbs(count: int = None):
        prefix = "datasets/wxbs_benchmark/.WxBS/v1.1"
        wxbs_path = ROOT / prefix
        pairs = []
        for catg in os.listdir(wxbs_path):
            catg_path = wxbs_path / catg
            if not catg_path.is_dir():
                continue
            for scene in os.listdir(catg_path):
                scene_path = catg_path / scene
                if not scene_path.is_dir():
                    continue
                img1_path = scene_path / "01.png"
                img2_path = scene_path / "02.png"
                if img1_path.exists() and img2_path.exists():
                    pairs.append([str(img1_path), str(img2_path)])
        return pairs

    # image pair path
    pairs = gen_images_pairs()
    pairs += gen_rot_image_pairs()
    pairs += gen_scale_image_pairs()
    pairs += gen_image_pairs_wxbs()

    match_setting_threshold = DEFAULT_SETTING_THRESHOLD
    match_setting_max_features = DEFAULT_SETTING_MAX_FEATURES
    detect_keypoints_threshold = DEFAULT_DEFAULT_KEYPOINT_THRESHOLD
    ransac_method = DEFAULT_RANSAC_METHOD
    ransac_reproj_threshold = DEFAULT_RANSAC_REPROJ_THRESHOLD
    ransac_confidence = DEFAULT_RANSAC_CONFIDENCE
    ransac_max_iter = DEFAULT_RANSAC_MAX_ITER
    input_lists = []
    dist_examples = distribute_elements(pairs, example_matchers)
    for pair, mt in zip(pairs, dist_examples):
        input_lists.append(
            [
                pair[0],
                pair[1],
                match_setting_threshold,
                match_setting_max_features,
                detect_keypoints_threshold,
                mt,
                # enable_ransac,
                ransac_method,
                ransac_reproj_threshold,
                ransac_confidence,
                ransac_max_iter,
            ]
        )
    return input_lists


def set_null_pred(feature_type: str, pred: dict):
    if feature_type == "KEYPOINT":
        pred["mmkeypoints0_orig"] = np.array([])
        pred["mmkeypoints1_orig"] = np.array([])
        pred["mmconf"] = np.array([])
    elif feature_type == "LINE":
        pred["mline_keypoints0_orig"] = np.array([])
        pred["mline_keypoints1_orig"] = np.array([])
    pred["H"] = None
    pred["geom_info"] = {}
    return pred


def _filter_matches_opencv(
    kp0: np.ndarray,
    kp1: np.ndarray,
    method: int = cv2.RANSAC,
    reproj_threshold: float = 3.0,
    confidence: float = 0.99,
    max_iter: int = 2000,
    geometry_type: str = "Homography",
) -> Tuple[np.ndarray, np.ndarray]:
    """
    Filters matches between two sets of keypoints using OpenCV's findHomography.

    Args:
        kp0 (np.ndarray): Array of keypoints from the first image.
        kp1 (np.ndarray): Array of keypoints from the second image.
        method (int, optional): RANSAC method. Defaults to "cv2.RANSAC".
        reproj_threshold (float, optional): RANSAC reprojection threshold. Defaults to 3.0.
        confidence (float, optional): RANSAC confidence. Defaults to 0.99.
        max_iter (int, optional): RANSAC maximum iterations. Defaults to 2000.
        geometry_type (str, optional): Type of geometry. Defaults to "Homography".

    Returns:
        Tuple[np.ndarray, np.ndarray]: Homography matrix and mask.
    """
    if geometry_type == "Homography":
        M, mask = cv2.findHomography(
            kp0,
            kp1,
            method=method,
            ransacReprojThreshold=reproj_threshold,
            confidence=confidence,
            maxIters=max_iter,
        )
    elif geometry_type == "Fundamental":
        M, mask = cv2.findFundamentalMat(
            kp0,
            kp1,
            method=method,
            ransacReprojThreshold=reproj_threshold,
            confidence=confidence,
            maxIters=max_iter,
        )
    mask = np.array(mask.ravel().astype("bool"), dtype="bool")
    return M, mask


def _filter_matches_poselib(
    kp0: np.ndarray,
    kp1: np.ndarray,
    method: int = None,  # not used
    reproj_threshold: float = 3,
    confidence: float = 0.99,
    max_iter: int = 2000,
    geometry_type: str = "Homography",
) -> dict:
    """
    Filters matches between two sets of keypoints using the poselib library.

    Args:
        kp0 (np.ndarray): Array of keypoints from the first image.
        kp1 (np.ndarray): Array of keypoints from the second image.
        method (str, optional): RANSAC method. Defaults to "RANSAC".
        reproj_threshold (float, optional): RANSAC reprojection threshold. Defaults to 3.
        confidence (float, optional): RANSAC confidence. Defaults to 0.99.
        max_iter (int, optional): RANSAC maximum iterations. Defaults to 2000.
        geometry_type (str, optional): Type of geometry. Defaults to "Homography".

    Returns:
        dict: Information about the homography estimation.
    """
    ransac_options = {
        "max_iterations": max_iter,
        # "min_iterations":  min_iter,
        "success_prob": confidence,
        "max_reproj_error": reproj_threshold,
        # "progressive_sampling": args.sampler.lower() == 'prosac'
    }

    if geometry_type == "Homography":
        M, info = poselib.estimate_homography(kp0, kp1, ransac_options)
    elif geometry_type == "Fundamental":
        M, info = poselib.estimate_fundamental(kp0, kp1, ransac_options)
    else:
        raise NotImplementedError

    return M, np.array(info["inliers"])


def proc_ransac_matches(
    mkpts0: np.ndarray,
    mkpts1: np.ndarray,
    ransac_method: str = DEFAULT_RANSAC_METHOD,
    ransac_reproj_threshold: float = 3.0,
    ransac_confidence: float = 0.99,
    ransac_max_iter: int = 2000,
    geometry_type: str = "Homography",
):
    if ransac_method.startswith("CV2"):
        logger.info(
            f"ransac_method: {ransac_method}, geometry_type: {geometry_type}"
        )
        return _filter_matches_opencv(
            mkpts0,
            mkpts1,
            ransac_zoo[ransac_method],
            ransac_reproj_threshold,
            ransac_confidence,
            ransac_max_iter,
            geometry_type,
        )
    elif ransac_method.startswith("POSELIB"):
        logger.info(
            f"ransac_method: {ransac_method}, geometry_type: {geometry_type}"
        )
        return _filter_matches_poselib(
            mkpts0,
            mkpts1,
            None,
            ransac_reproj_threshold,
            ransac_confidence,
            ransac_max_iter,
            geometry_type,
        )
    else:
        raise NotImplementedError


def filter_matches(
    pred: Dict[str, Any],
    ransac_method: str = DEFAULT_RANSAC_METHOD,
    ransac_reproj_threshold: float = DEFAULT_RANSAC_REPROJ_THRESHOLD,
    ransac_confidence: float = DEFAULT_RANSAC_CONFIDENCE,
    ransac_max_iter: int = DEFAULT_RANSAC_MAX_ITER,
    ransac_estimator: str = None,
):
    """
    Filter matches using RANSAC. If keypoints are available, filter by keypoints.
    If lines are available, filter by lines. If both keypoints and lines are
    available, filter by keypoints.

    Args:
        pred (Dict[str, Any]): dict of matches, including original keypoints.
        ransac_method (str, optional): RANSAC method. Defaults to DEFAULT_RANSAC_METHOD.
        ransac_reproj_threshold (float, optional): RANSAC reprojection threshold. Defaults to DEFAULT_RANSAC_REPROJ_THRESHOLD.
        ransac_confidence (float, optional): RANSAC confidence. Defaults to DEFAULT_RANSAC_CONFIDENCE.
        ransac_max_iter (int, optional): RANSAC maximum iterations. Defaults to DEFAULT_RANSAC_MAX_ITER.

    Returns:
        Dict[str, Any]: filtered matches.
    """
    mkpts0: Optional[np.ndarray] = None
    mkpts1: Optional[np.ndarray] = None
    feature_type: Optional[str] = None
    if "mkeypoints0_orig" in pred.keys() and "mkeypoints1_orig" in pred.keys():
        mkpts0 = pred["mkeypoints0_orig"]
        mkpts1 = pred["mkeypoints1_orig"]
        feature_type = "KEYPOINT"
    elif (
        "line_keypoints0_orig" in pred.keys()
        and "line_keypoints1_orig" in pred.keys()
    ):
        mkpts0 = pred["line_keypoints0_orig"]
        mkpts1 = pred["line_keypoints1_orig"]
        feature_type = "LINE"
    else:
        return set_null_pred(feature_type, pred)
    if mkpts0 is None or mkpts0 is None:
        return set_null_pred(feature_type, pred)
    if ransac_method not in ransac_zoo.keys():
        ransac_method = DEFAULT_RANSAC_METHOD

    if len(mkpts0) < DEFAULT_MIN_NUM_MATCHES:
        return set_null_pred(feature_type, pred)

    geom_info = compute_geometry(
        pred,
        ransac_method=ransac_method,
        ransac_reproj_threshold=ransac_reproj_threshold,
        ransac_confidence=ransac_confidence,
        ransac_max_iter=ransac_max_iter,
    )

    if "Homography" in geom_info.keys():
        mask = geom_info["mask_h"]
        if feature_type == "KEYPOINT":
            pred["mmkeypoints0_orig"] = mkpts0[mask]
            pred["mmkeypoints1_orig"] = mkpts1[mask]
            pred["mmconf"] = pred["mconf"][mask]
        elif feature_type == "LINE":
            pred["mline_keypoints0_orig"] = mkpts0[mask]
            pred["mline_keypoints1_orig"] = mkpts1[mask]
        pred["H"] = np.array(geom_info["Homography"])
    else:
        set_null_pred(feature_type, pred)
    # do not show mask
    geom_info.pop("mask_h", None)
    geom_info.pop("mask_f", None)
    pred["geom_info"] = geom_info
    return pred


def compute_geometry(
    pred: Dict[str, Any],
    ransac_method: str = DEFAULT_RANSAC_METHOD,
    ransac_reproj_threshold: float = DEFAULT_RANSAC_REPROJ_THRESHOLD,
    ransac_confidence: float = DEFAULT_RANSAC_CONFIDENCE,
    ransac_max_iter: int = DEFAULT_RANSAC_MAX_ITER,
) -> Dict[str, List[float]]:
    """
    Compute geometric information of matches, including Fundamental matrix,
    Homography matrix, and rectification matrices (if available).

    Args:
        pred (Dict[str, Any]): dict of matches, including original keypoints.
        ransac_method (str, optional): RANSAC method. Defaults to DEFAULT_RANSAC_METHOD.
        ransac_reproj_threshold (float, optional): RANSAC reprojection threshold. Defaults to DEFAULT_RANSAC_REPROJ_THRESHOLD.
        ransac_confidence (float, optional): RANSAC confidence. Defaults to DEFAULT_RANSAC_CONFIDENCE.
        ransac_max_iter (int, optional): RANSAC maximum iterations. Defaults to DEFAULT_RANSAC_MAX_ITER.

    Returns:
        Dict[str, List[float]]: geometric information in form of a dict.
    """
    mkpts0: Optional[np.ndarray] = None
    mkpts1: Optional[np.ndarray] = None

    if "mkeypoints0_orig" in pred.keys() and "mkeypoints1_orig" in pred.keys():
        mkpts0 = pred["mkeypoints0_orig"]
        mkpts1 = pred["mkeypoints1_orig"]
    elif (
        "line_keypoints0_orig" in pred.keys()
        and "line_keypoints1_orig" in pred.keys()
    ):
        mkpts0 = pred["line_keypoints0_orig"]
        mkpts1 = pred["line_keypoints1_orig"]

    if mkpts0 is not None and mkpts1 is not None:
        if len(mkpts0) < 2 * DEFAULT_MIN_NUM_MATCHES:
            return {}
        geo_info: Dict[str, List[float]] = {}

        F, mask_f = proc_ransac_matches(
            mkpts0,
            mkpts1,
            ransac_method,
            ransac_reproj_threshold,
            ransac_confidence,
            ransac_max_iter,
            geometry_type="Fundamental",
        )

        if F is not None:
            geo_info["Fundamental"] = F.tolist()
            geo_info["mask_f"] = mask_f
        H, mask_h = proc_ransac_matches(
            mkpts1,
            mkpts0,
            ransac_method,
            ransac_reproj_threshold,
            ransac_confidence,
            ransac_max_iter,
            geometry_type="Homography",
        )

        h0, w0, _ = pred["image0_orig"].shape
        if H is not None:
            geo_info["Homography"] = H.tolist()
            geo_info["mask_h"] = mask_h
            try:
                _, H1, H2 = cv2.stereoRectifyUncalibrated(
                    mkpts0.reshape(-1, 2),
                    mkpts1.reshape(-1, 2),
                    F,
                    imgSize=(w0, h0),
                )
                geo_info["H1"] = H1.tolist()
                geo_info["H2"] = H2.tolist()
            except cv2.error as e:
                logger.error(
                    f"StereoRectifyUncalibrated failed, skip! error: {e}"
                )
        return geo_info
    else:
        return {}


def wrap_images(
    img0: np.ndarray,
    img1: np.ndarray,
    geo_info: Optional[Dict[str, List[float]]],
    geom_type: str,
) -> Tuple[Optional[str], Optional[Dict[str, List[float]]]]:
    """
    Wraps the images based on the geometric transformation used to align them.

    Args:
        img0: numpy array representing the first image.
        img1: numpy array representing the second image.
        geo_info: dictionary containing the geometric transformation information.
        geom_type: type of geometric transformation used to align the images.

    Returns:
        A tuple containing a base64 encoded image string and a dictionary with the transformation matrix.
    """
    h0, w0, _ = img0.shape
    h1, w1, _ = img1.shape
    if geo_info is not None and len(geo_info) != 0:
        rectified_image0 = img0
        rectified_image1 = None
        if "Homography" not in geo_info:
            logger.warning(f"{geom_type} not exist, maybe too less matches")
            return None, None

        H = np.array(geo_info["Homography"])

        title: List[str] = []
        if geom_type == "Homography":
            rectified_image1 = cv2.warpPerspective(img1, H, (w0, h0))
            title = ["Image 0", "Image 1 - warped"]
        elif geom_type == "Fundamental":
            if geom_type not in geo_info:
                logger.warning(f"{geom_type} not exist, maybe too less matches")
                return None, None
            else:
                H1, H2 = np.array(geo_info["H1"]), np.array(geo_info["H2"])
                rectified_image0 = cv2.warpPerspective(img0, H1, (w0, h0))
                rectified_image1 = cv2.warpPerspective(img1, H2, (w1, h1))
                title = ["Image 0 - warped", "Image 1 - warped"]
        else:
            print("Error: Unknown geometry type")
        fig = plot_images(
            [rectified_image0.squeeze(), rectified_image1.squeeze()],
            title,
            dpi=300,
        )
        return fig2im(fig), rectified_image1
    else:
        return None, None


def generate_warp_images(
    input_image0: np.ndarray,
    input_image1: np.ndarray,
    matches_info: Dict[str, Any],
    choice: str,
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]:
    """
    Changes the estimate of the geometric transformation used to align the images.

    Args:
        input_image0: First input image.
        input_image1: Second input image.
        matches_info: Dictionary containing information about the matches.
        choice: Type of geometric transformation to use ('Homography' or 'Fundamental') or 'No' to disable.

    Returns:
        A tuple containing the updated images and the warpped images.
    """
    if (
        matches_info is None
        or len(matches_info) < 1
        or "geom_info" not in matches_info.keys()
    ):
        return None, None
    geom_info = matches_info["geom_info"]
    warped_image = None
    if choice != "No":
        wrapped_image_pair, warped_image = wrap_images(
            input_image0, input_image1, geom_info, choice
        )
        return wrapped_image_pair, warped_image
    else:
        return None, None


def send_to_match(state_cache: Dict[str, Any]):
    """
    Send the state cache to the match function.

    Args:
        state_cache (Dict[str, Any]): Current state of the app.

    Returns:
        None
    """
    if state_cache:
        return (
            state_cache["image0_orig"],
            state_cache["wrapped_image"],
        )
    else:
        return None, None


def run_ransac(
    state_cache: Dict[str, Any],
    choice_geometry_type: str,
    ransac_method: str = DEFAULT_RANSAC_METHOD,
    ransac_reproj_threshold: int = DEFAULT_RANSAC_REPROJ_THRESHOLD,
    ransac_confidence: float = DEFAULT_RANSAC_CONFIDENCE,
    ransac_max_iter: int = DEFAULT_RANSAC_MAX_ITER,
) -> Tuple[Optional[np.ndarray], Optional[Dict[str, int]]]:
    """
    Run RANSAC matches and return the output images and the number of matches.

    Args:
        state_cache (Dict[str, Any]): Current state of the app, including the matches.
        ransac_method (str, optional): RANSAC method. Defaults to DEFAULT_RANSAC_METHOD.
        ransac_reproj_threshold (int, optional): RANSAC reprojection threshold. Defaults to DEFAULT_RANSAC_REPROJ_THRESHOLD.
        ransac_confidence (float, optional): RANSAC confidence. Defaults to DEFAULT_RANSAC_CONFIDENCE.
        ransac_max_iter (int, optional): RANSAC maximum iterations. Defaults to DEFAULT_RANSAC_MAX_ITER.

    Returns:
        Tuple[Optional[np.ndarray], Optional[Dict[str, int]]]: Tuple containing the output images and the number of matches.
    """
    if not state_cache:
        logger.info("Run Match first before Rerun RANSAC")
        gr.Warning("Run Match first before Rerun RANSAC")
        return None, None
    t1 = time.time()
    logger.info(
        f"Run RANSAC matches using: {ransac_method} with threshold: {ransac_reproj_threshold}"
    )
    logger.info(
        f"Run RANSAC matches using: {ransac_confidence} with iter: {ransac_max_iter}"
    )
    # if enable_ransac:
    filter_matches(
        state_cache,
        ransac_method=ransac_method,
        ransac_reproj_threshold=ransac_reproj_threshold,
        ransac_confidence=ransac_confidence,
        ransac_max_iter=ransac_max_iter,
    )
    logger.info(f"RANSAC matches done using: {time.time()-t1:.3f}s")
    t1 = time.time()

    # plot images with ransac matches
    titles = [
        "Image 0 - Ransac matched keypoints",
        "Image 1 - Ransac matched keypoints",
    ]
    output_matches_ransac, num_matches_ransac = display_matches(
        state_cache, titles=titles, tag="KPTS_RANSAC"
    )
    logger.info(f"Display matches done using: {time.time()-t1:.3f}s")
    t1 = time.time()

    # compute warp images
    output_wrapped, warped_image = generate_warp_images(
        state_cache["image0_orig"],
        state_cache["image1_orig"],
        state_cache,
        choice_geometry_type,
    )
    plt.close("all")

    num_matches_raw = state_cache["num_matches_raw"]
    state_cache["wrapped_image"] = warped_image

    # tmp_state_cache = tempfile.NamedTemporaryFile(suffix='.pkl', delete=False)
    tmp_state_cache = "output.pkl"
    with open(tmp_state_cache, "wb") as f:
        pickle.dump(state_cache, f)

    logger.info("Dump results done!")

    return (
        output_matches_ransac,
        {
            "num_matches_raw": num_matches_raw,
            "num_matches_ransac": num_matches_ransac,
        },
        output_wrapped,
        tmp_state_cache,
    )


def run_matching(
    image0: np.ndarray,
    image1: np.ndarray,
    match_threshold: float,
    extract_max_keypoints: int,
    keypoint_threshold: float,
    key: str,
    ransac_method: str = DEFAULT_RANSAC_METHOD,
    ransac_reproj_threshold: int = DEFAULT_RANSAC_REPROJ_THRESHOLD,
    ransac_confidence: float = DEFAULT_RANSAC_CONFIDENCE,
    ransac_max_iter: int = DEFAULT_RANSAC_MAX_ITER,
    choice_geometry_type: str = DEFAULT_SETTING_GEOMETRY,
    matcher_zoo: Dict[str, Any] = None,
    use_cached_model: bool = False,
) -> Tuple[
    np.ndarray,
    np.ndarray,
    np.ndarray,
    Dict[str, int],
    Dict[str, Dict[str, Any]],
    Dict[str, Dict[str, float]],
    np.ndarray,
]:
    """Match two images using the given parameters.

    Args:
        image0 (np.ndarray): RGB image 0.
        image1 (np.ndarray): RGB image 1.
        match_threshold (float): match threshold.
        extract_max_keypoints (int): number of keypoints to extract.
        keypoint_threshold (float): keypoint threshold.
        key (str): key of the model to use.
        ransac_method (str, optional): RANSAC method to use.
        ransac_reproj_threshold (int, optional): RANSAC reprojection threshold.
        ransac_confidence (float, optional): RANSAC confidence level.
        ransac_max_iter (int, optional): RANSAC maximum number of iterations.
        choice_geometry_type (str, optional): setting of geometry estimation.

    Returns:
        tuple:
            - output_keypoints (np.ndarray): image with keypoints.
            - output_matches_raw (np.ndarray): image with raw matches.
            - output_matches_ransac (np.ndarray): image with RANSAC matches.
            - num_matches (Dict[str, int]): number of raw and RANSAC matches.
            - configs (Dict[str, Dict[str, Any]]): match and feature extraction configs.
            - geom_info (Dict[str, Dict[str, float]]): geometry information.
            - output_wrapped (np.ndarray): wrapped images.
    """
    # image0 and image1 is RGB mode
    if image0 is None or image1 is None:
        logger.error(
            "Error: No images found! Please upload two images or select an example."
        )
        raise gr.Error(
            "Error: No images found! Please upload two images or select an example."
        )
    # init output
    output_keypoints = None
    output_matches_raw = None
    output_matches_ransac = None

    # super slow!
    if "roma" in key.lower() and DEVICE == "cpu":
        gr.Info(
            f"Success! Please be patient and allow for about 2-3 minutes."
            f" Due to CPU inference, {key} is quiet slow."
        )
    t0 = time.time()
    model = matcher_zoo[key]
    match_conf = model["matcher"]
    # update match config
    match_conf["model"]["match_threshold"] = match_threshold
    match_conf["model"]["max_keypoints"] = extract_max_keypoints
    cache_key = "{}_{}".format(key, match_conf["model"]["name"])
    if use_cached_model:
        # because of the model cache, we need to update the config
        matcher = model_cache.cache_model(cache_key, get_model, match_conf)
        matcher.conf["max_keypoints"] = extract_max_keypoints
        matcher.conf["match_threshold"] = match_threshold
        logger.info(f"Loaded cached model {cache_key}")
    else:
        matcher = get_model(match_conf)
    logger.info(f"Loading model using: {time.time()-t0:.3f}s")
    t1 = time.time()

    if model["dense"]:
        pred = match_dense.match_images(
            matcher, image0, image1, match_conf["preprocessing"], device=DEVICE
        )
        del matcher
        extract_conf = None
    else:
        extract_conf = model["feature"]
        # update extract config
        extract_conf["model"]["max_keypoints"] = extract_max_keypoints
        extract_conf["model"]["keypoint_threshold"] = keypoint_threshold
        cache_key = "{}_{}".format(key, extract_conf["model"]["name"])

        if use_cached_model:
            extractor = model_cache.cache_model(
                cache_key, get_feature_model, extract_conf
            )
            # because of the model cache, we need to update the config
            extractor.conf["max_keypoints"] = extract_max_keypoints
            extractor.conf["keypoint_threshold"] = keypoint_threshold
            logger.info(f"Loaded cached model {cache_key}")
        else:
            extractor = get_feature_model(extract_conf)

        pred0 = extract_features.extract(
            extractor, image0, extract_conf["preprocessing"]
        )
        pred1 = extract_features.extract(
            extractor, image1, extract_conf["preprocessing"]
        )
        pred = match_features.match_images(matcher, pred0, pred1)
        del extractor
    gr.Info(
        f"Matching images done using: {time.time()-t1:.3f}s",
    )
    logger.info(f"Matching images done using: {time.time()-t1:.3f}s")
    t1 = time.time()

    # plot images with keypoints
    titles = [
        "Image 0 - Keypoints",
        "Image 1 - Keypoints",
    ]
    output_keypoints = display_keypoints(pred, titles=titles)

    # plot images with raw matches
    titles = [
        "Image 0 - Raw matched keypoints",
        "Image 1 - Raw matched keypoints",
    ]
    output_matches_raw, num_matches_raw = display_matches(pred, titles=titles)

    # if enable_ransac:
    filter_matches(
        pred,
        ransac_method=ransac_method,
        ransac_reproj_threshold=ransac_reproj_threshold,
        ransac_confidence=ransac_confidence,
        ransac_max_iter=ransac_max_iter,
    )

    # gr.Info(f"RANSAC matches done using: {time.time()-t1:.3f}s")
    logger.info(f"RANSAC matches done using: {time.time()-t1:.3f}s")
    t1 = time.time()

    # plot images with ransac matches
    titles = [
        "Image 0 - Ransac matched keypoints",
        "Image 1 - Ransac matched keypoints",
    ]
    output_matches_ransac, num_matches_ransac = display_matches(
        pred, titles=titles, tag="KPTS_RANSAC"
    )
    # gr.Info(f"Display matches done using: {time.time()-t1:.3f}s")
    logger.info(f"Display matches done using: {time.time()-t1:.3f}s")

    t1 = time.time()
    # plot wrapped images
    output_wrapped, warped_image = generate_warp_images(
        pred["image0_orig"],
        pred["image1_orig"],
        pred,
        choice_geometry_type,
    )
    plt.close("all")
    # gr.Info(f"In summary, total time: {time.time()-t0:.3f}s")
    logger.info(f"TOTAL time: {time.time()-t0:.3f}s")

    state_cache = pred
    state_cache["num_matches_raw"] = num_matches_raw
    state_cache["num_matches_ransac"] = num_matches_ransac
    state_cache["wrapped_image"] = warped_image

    # tmp_state_cache = tempfile.NamedTemporaryFile(suffix='.pkl', delete=False)
    tmp_state_cache = "output.pkl"
    with open(tmp_state_cache, "wb") as f:
        pickle.dump(state_cache, f)
    logger.info("Dump results done!")
    return (
        output_keypoints,
        output_matches_raw,
        output_matches_ransac,
        {
            "num_raw_matches": num_matches_raw,
            "num_ransac_matches": num_matches_ransac,
        },
        {
            "match_conf": match_conf,
            "extractor_conf": extract_conf,
        },
        {
            "geom_info": pred.get("geom_info", {}),
        },
        output_wrapped,
        state_cache,
        tmp_state_cache,
    )


# @ref: https://docs.opencv.org/4.x/d0/d74/md__build_4_x-contrib_docs-lin64_opencv_doc_tutorials_calib3d_usac.html
# AND: https://opencv.org/blog/2021/06/09/evaluating-opencvs-new-ransacs
ransac_zoo = {
    "POSELIB": "LO-RANSAC",
    "CV2_RANSAC": cv2.RANSAC,
    "CV2_USAC_MAGSAC": cv2.USAC_MAGSAC,
    "CV2_USAC_DEFAULT": cv2.USAC_DEFAULT,
    "CV2_USAC_FM_8PTS": cv2.USAC_FM_8PTS,
    "CV2_USAC_PROSAC": cv2.USAC_PROSAC,
    "CV2_USAC_FAST": cv2.USAC_FAST,
    "CV2_USAC_ACCURATE": cv2.USAC_ACCURATE,
    "CV2_USAC_PARALLEL": cv2.USAC_PARALLEL,
}


def rotate_image(input_path, degrees, output_path):
    img = Image.open(input_path)
    img_rotated = img.rotate(-degrees)
    img_rotated.save(output_path)


def scale_image(input_path, scale_factor, output_path):
    img = Image.open(input_path)
    width, height = img.size
    new_width = int(width * scale_factor)
    new_height = int(height * scale_factor)
    new_img = Image.new("RGB", (width, height), (0, 0, 0))
    img_resized = img.resize((new_width, new_height))
    position = ((width - new_width) // 2, (height - new_height) // 2)
    new_img.paste(img_resized, position)
    new_img.save(output_path)