This commit is contained in:
HuangHai
2026-01-13 20:54:49 +08:00
parent 6a11893d07
commit ddb63403b7
7 changed files with 168 additions and 45 deletions

View File

@@ -98,6 +98,96 @@ def save_image(path, img):
logger.error(f"Error saving image {path}: {e}")
return False
def detect_cards_cv(image_path, top_ratio=0.15, bottom_ratio=0.1):
"""
使用计算机图形学 (OpenCV) 检测列表中的场站卡片
方案:以 nav.jpg 为锚点,向上/下探测白色卡片边界
"""
img = read_image(image_path)
if img is None:
return []
h, w = img.shape[:2]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 1. 模板匹配查找锚点 (nav.jpg)
template_path = os.path.join(os.path.dirname(__file__), "Template", "nav.jpg")
anchors = []
if os.path.exists(template_path):
template = read_image(template_path)
if template is not None:
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
# 去重记录锚点中心
t_h, t_w = template.shape[:2]
matched_points = []
for pt in zip(*loc[::-1]): # (x, y)
is_duplicate = False
for mx, my in matched_points:
if abs(mx - pt[0]) < 50 and abs(my - pt[1]) < 50:
is_duplicate = True
break
if not is_duplicate:
matched_points.append(pt)
anchors.append((pt[0] + t_w // 2, pt[1] + t_h // 2))
logger.info(f"通过模板匹配找到 {len(anchors)} 个锚点")
# 2. 基于锚点向上/下扩张探测边界
# 计算每一行的平均亮度,用于探测背景
row_means = np.mean(gray[:, int(w*0.2):int(w*0.8)], axis=1)
cards = []
for ax, ay in anchors:
# 向上探测:直到亮度低于 245 (进入灰色背景)
y1 = ay
while y1 > h * top_ratio:
if row_means[int(y1)] < 245:
break
y1 -= 1
# 向下探测:直到亮度低于 245
y2 = ay
while y2 < h * (1 - bottom_ratio):
if row_means[int(y2)] < 245:
break
y2 += 1
# 验证卡片高度是否合理
if y2 - y1 > 150:
# 给 y 坐标增加一点 padding
cards.append([int(w * 0.05), int(y1 + 5), int(w * 0.95), int(y2 - 5)])
# 3. 兜底方案:如果模板匹配没找到,使用之前的投影法
if not cards:
logger.warning("模板匹配未找到卡片,尝试投影法兜底...")
_, binary = cv2.threshold(gray, 250, 255, cv2.THRESH_BINARY)
top = int(h * top_ratio)
bottom = int(h * (1 - bottom_ratio))
roi_binary = binary[:, int(w*0.2):int(w*0.8)]
row_white_counts = np.sum(roi_binary == 255, axis=1)
threshold_count = (int(w*0.8) - int(w*0.2)) * 0.9
is_card_row = row_white_counts > threshold_count
start_y = None
for y in range(top, bottom):
if is_card_row[y]:
if start_y is None: start_y = y
else:
if start_y is not None:
if y - start_y > 150:
cards.append([int(w * 0.05), start_y + 10, int(w * 0.95), y - 10])
start_y = None
if start_y is not None and bottom - start_y > 150:
cards.append([int(w * 0.05), start_y + 10, int(w * 0.95), bottom - 10])
# 4. 排序
cards.sort(key=lambda c: c[1])
logger.info(f"最终检测到 {len(cards)} 个场站卡片区域")
return cards
def clear_temp_dir(save_dir=None):
"""清空临时目录中的所有文件"""
if save_dir is None:
@@ -141,7 +231,7 @@ def draw_rectangles(image_path, points, output_path=None):
if not DRAW_DEBUG_BOXES:
return image_path
img = cv2.imread(image_path)
img = read_image(image_path)
if img is None:
return image_path
@@ -153,7 +243,7 @@ def draw_rectangles(image_path, points, output_path=None):
cv2.circle(img, center, 10, DEBUG_BOX_COLOR, -1)
save_path = output_path if output_path else image_path
cv2.imwrite(save_path, img)
save_image(save_path, img)
return save_path
except Exception as e:
logger.error(f"绘制矩形框失败: {e}")