search_engine.py
5.1 KB
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
"""Exact tenant recall followed by unchanged CNN/RANSAC fusion."""
from concurrent.futures import ThreadPoolExecutor
import logging
import threading
from .feature_extractor import FeatureExtractor
logger = logging.getLogger(__name__)
class ImageSearchEngine:
def __init__(self, db_path=None, config=None, index=None, db_manager=None, extractor=None):
from database import DatabaseManager
from .vector_index import VectorIndex, configured_dimension
self.config = config or {}
self.db = db_manager if db_manager is not None else DatabaseManager(db_path)
self.index = index if index is not None else VectorIndex(configured_dimension(self.config))
if index is None:
self.index.bulk_load(self.db.iter_index_rows())
self.extractor = extractor if extractor is not None else FeatureExtractor(
orb_max_features=self.config.get('orb_max_features', 1200),
cnn_enabled=self.config.get('cnn_enabled', True))
search_config = self.config.get('search', {})
self.max_candidates = search_config.get('max_candidates', 200)
self.ransac_top_k = search_config.get('ransac_top_k', 100)
self.top_results = search_config.get('top_results', 20)
ransac_config = search_config.get('ransac', {})
self.min_orb_inliers = ransac_config.get('min_inliers', 15)
self.ransac_reproj_thresh = ransac_config.get('reproj_threshold', 4.0)
self.ransac_confidence = ransac_config.get('confidence', 0.995)
weights_config = search_config.get('fusion_weights', {})
self.weights = {
"cnn": weights_config.get("cnn", 0.2) * 100,
"ransac": weights_config.get("ransac", 0.8) * 100
}
self.threads = search_config.get('threads', 4)
self.semaphore = threading.BoundedSemaphore(search_config.get('max_concurrent', 2))
def search(self, query_img_path, eps_id, top_k=None):
with self.semaphore:
return self._search(query_img_path, eps_id, self.top_results if top_k is None else top_k)
def _search(self, path, eps_id, top_k):
query = self.extractor.extract_all_features(path)
if query is None or query.get('cnn_vector') is None:
return []
recalled = self.index.search(query['cnn_vector'], eps_id, self.max_candidates)
rows = self.db.get_features([item[0] for item in recalled])
candidates = []
for rank, (design_id, cnn_sim, version) in enumerate(recalled):
row = rows.get(design_id)
if row is None or row['feat_version'] != version or row['eps_id'] != eps_id:
continue
candidates.append({'img_id': design_id, 'design_no': row['design_no'],
'image_url': row['image_url'], 'initial_score': cnn_sim * 100 * self.weights['cnn'],
'details': {'cnn_sim': cnn_sim, 'ransac_inliers': 0},
'row': row, 'use_ransac': rank < self.ransac_top_k})
def verify(candidate):
row = candidate['row']
if not candidate['use_ransac'] or row['orb_pts'] is None or row['orb_desc'] is None:
return 0
try:
return self.extractor.compute_orb_ransac_score(
(query['orb_kp'], query['orb_desc']), (row['orb_pts'], row['orb_desc']),
min_inliers=self.min_orb_inliers, ransac_thresh=self.ransac_reproj_thresh,
confidence=self.ransac_confidence)
except Exception:
logger.warning('RANSAC failed for design %s', candidate['img_id'])
return 0
with ThreadPoolExecutor(max_workers=self.threads) as executor:
for candidate, inliers in zip(candidates, executor.map(verify, candidates)):
candidate['details']['ransac_inliers'] = inliers
candidate['score'] = candidate['initial_score'] + inliers * self.weights['ransac']
candidate['confidence'] = self._assess_confidence(candidate)
del candidate['row']
del candidate['use_ransac']
candidates.sort(key=lambda c: (-c['score'], c['img_id']))
return candidates[:top_k]
def _assess_confidence(self, candidate):
"""
评估搜索结果的置信度(珠宝图片优化版)
针对变色和裁切场景优化的判断标准:
- high: RANSAC内点>=15(几何一致性强)或 CNN相似度>0.8
- medium: RANSAC内点>=8(降低要求)或 CNN相似度>0.7
- low: 其他
Args:
candidate: 候选结果字典
Returns:
str: "high", "medium", "low"
"""
details = candidate["details"]
ransac_inliers = details.get("ransac_inliers", 0)
cnn_sim = details.get("cnn_sim", 0.0)
# High confidence(几何一致性或语义确认)
if ransac_inliers >= 15 and cnn_sim > 0.8:
return "high"
# Medium confidence(降低要求以提升召回)
if ransac_inliers >= 8 and cnn_sim > 0.7:
return "medium"
# Low confidence
return "low"