Spaces:
No application file
No application file
Upload api.py
Browse files
api.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
from pathlib import Path
|
5 |
+
import tempfile
|
6 |
+
import os
|
7 |
+
import logging
|
8 |
+
from hloc import logger as hloc_logger
|
9 |
+
from common.api import ImageMatchingAPI
|
10 |
+
from common.utils import (
|
11 |
+
DEVICE,
|
12 |
+
get_matcher_zoo,
|
13 |
+
load_config,
|
14 |
+
ROOT,
|
15 |
+
)
|
16 |
+
|
17 |
+
app = Flask(__name__)
|
18 |
+
|
19 |
+
# Load configuration and matcher
|
20 |
+
config = load_config(ROOT / "common/config.yaml")
|
21 |
+
matcher_zoo_restored = get_matcher_zoo(config["matcher_zoo"])
|
22 |
+
conf = matcher_zoo_restored.get("superpoint+superglue")
|
23 |
+
api = ImageMatchingAPI(conf=conf, device=DEVICE)
|
24 |
+
|
25 |
+
# Set up logging
|
26 |
+
logging.basicConfig(level=logging.INFO)
|
27 |
+
logger = logging.getLogger(__name__)
|
28 |
+
|
29 |
+
def match_images(img_path1, img_path2):
|
30 |
+
logger.info(f"Matching images with {DEVICE}")
|
31 |
+
try:
|
32 |
+
# Read the images using OpenCV
|
33 |
+
image0 = cv2.imread(img_path1)
|
34 |
+
image1 = cv2.imread(img_path2)
|
35 |
+
|
36 |
+
if image0 is None or image1 is None:
|
37 |
+
raise ValueError("One or both images could not be read. Ensure the files are valid images.")
|
38 |
+
|
39 |
+
# Convert BGR to RGB
|
40 |
+
image0 = cv2.cvtColor(image0, cv2.COLOR_BGR2RGB)
|
41 |
+
image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
|
42 |
+
|
43 |
+
results = api(image0, image1)
|
44 |
+
|
45 |
+
return {
|
46 |
+
"num_keypoints0": len(results["keypoints0_orig"]),
|
47 |
+
"num_keypoints1": len(results["keypoints1_orig"]),
|
48 |
+
"num_matches": len(results["mkeypoints0_orig"]),
|
49 |
+
"num_inliers": len(results["mmkeypoints0_orig"]),
|
50 |
+
"keypoints0": results["keypoints0_orig"].tolist(),
|
51 |
+
"keypoints1": results["keypoints1_orig"].tolist(),
|
52 |
+
"matches0": results["mkeypoints0_orig"].tolist(),
|
53 |
+
"matches1": results["mmkeypoints0_orig"].tolist(),
|
54 |
+
"inliers0": results["mmkeypoints0_orig"].tolist(),
|
55 |
+
"inliers1": results["mmkeypoints1_orig"].tolist(),
|
56 |
+
"confidence": results["mconf"].tolist(),
|
57 |
+
"inlier_confidence": results["mmconf"].tolist(),
|
58 |
+
}
|
59 |
+
except Exception as e:
|
60 |
+
logger.error("Matching failed: %s", str(e))
|
61 |
+
return {"error": str(e)}
|
62 |
+
finally:
|
63 |
+
try:
|
64 |
+
os.remove(img_path1)
|
65 |
+
os.remove(img_path2)
|
66 |
+
except Exception as cleanup_error:
|
67 |
+
logger.error("Failed to clean up temporary files: %s", str(cleanup_error))
|
68 |
+
|
69 |
+
@app.route('/match-images', methods=['POST'])
|
70 |
+
def match_images_endpoint():
|
71 |
+
if 'img1' not in request.files or 'img2' not in request.files:
|
72 |
+
return jsonify({"error": "Please upload both images."}), 400
|
73 |
+
|
74 |
+
img1_file = request.files['img1']
|
75 |
+
img2_file = request.files['img2']
|
76 |
+
|
77 |
+
# Validate file types
|
78 |
+
valid_extensions = {'png', 'jpg', 'jpeg', 'bmp', 'tiff'}
|
79 |
+
if not (img1_file.filename.split('.')[-1].lower() in valid_extensions and
|
80 |
+
img2_file.filename.split('.')[-1].lower() in valid_extensions):
|
81 |
+
return jsonify({"error": "Invalid file type. Please upload images in one of the following formats: png, jpg, jpeg, bmp, tiff"}), 400
|
82 |
+
|
83 |
+
try:
|
84 |
+
# Save the uploaded files to a temporary directory with unique filenames
|
85 |
+
temp_dir = tempfile.mkdtemp()
|
86 |
+
img_path1 = os.path.join(temp_dir, next(tempfile._get_candidate_names()) + os.path.splitext(img1_file.filename)[1])
|
87 |
+
img_path2 = os.path.join(temp_dir, next(tempfile._get_candidate_names()) + os.path.splitext(img2_file.filename)[1])
|
88 |
+
img1_file.save(img_path1)
|
89 |
+
img2_file.save(img_path2)
|
90 |
+
|
91 |
+
# Run the matching task synchronously
|
92 |
+
result = match_images(img_path1, img_path2)
|
93 |
+
except Exception as e:
|
94 |
+
logger.error("Error processing images: %s", str(e))
|
95 |
+
return jsonify({"error": str(e)}), 500
|
96 |
+
finally:
|
97 |
+
# Clean up the temporary directory
|
98 |
+
if os.path.exists(temp_dir):
|
99 |
+
try:
|
100 |
+
os.rmdir(temp_dir)
|
101 |
+
except Exception as cleanup_error:
|
102 |
+
logger.error("Failed to clean up temporary directory: %s", str(cleanup_error))
|
103 |
+
|
104 |
+
return jsonify(result), 200
|
105 |
+
|
106 |
+
if __name__ == '__main__':
|
107 |
+
app.run(debug=True)
|