import cv2 import numpy as np from matplotlib import pyplot as plt def lr_match(left_path, right_path): left_img = cv2.imread(left_path) right_img = cv2.imread(right_path) # 配准 left_gray = cv2.cvtColor(left_img, cv2.COLOR_BGR2GRAY) right_gray = cv2.cvtColor(right_img, cv2.COLOR_BGR2GRAY) h, w = left_gray.shape print(f"图像尺寸: 宽度={w}像素, 高度={h}像素") template = left_gray[100:h - 100, w - 100:w] print(f"模板区域: 上边界=100, 下边界={h - 100}, 左边界={w - 100}, 右边界={w}") search_area = right_gray[:, :200] print(f"搜索区域: 宽度={200}, 高度={h}") res = cv2.matchTemplate(search_area, template, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) print(f"匹配质量: {max_val:.4f} (1.0=完美匹配)") match_x, match_y = max_loc print(f"匹配位置: x={match_x}, y={match_y} (在搜索区域内)") dx = w - 100 - match_x dy = 100 - match_y print(f"计算平移量: dx={dx}, dy={dy}") return dx, dy def tb_match(top_path, bottom_path): top_img = cv2.imread(top_path) bottom_img = cv2.imread(bottom_path) # 配准 top_gray = cv2.cvtColor(top_img, cv2.COLOR_BGR2GRAY) bottom_gray = cv2.cvtColor(bottom_img, cv2.COLOR_BGR2GRAY) h, w = top_gray.shape print(f"图像尺寸: 宽度={w}像素, 高度={h}像素") template = top_gray[h - 100:h, 100:w - 100] print(f"模板区域: 上边界={h - 100}, 下边界={h}, 左边界={100}, 右边界={w - 100}") search_area = bottom_gray[:200, :] print(f"搜索区域: 宽度={w}, 高度={200}") res = cv2.matchTemplate(search_area, template, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) print(f"匹配质量: {max_val:.4f} (1.0=完美匹配)") match_x, match_y = max_loc print(f"匹配位置: x={match_x}, y={match_y} (在搜索区域内)") dx = 100 - match_x dy = h - 100 - match_y print(f"计算平移量: dx={dx}, dy={dy}") return dx, dy if __name__ == "__main__": row, col = 10, 10 left_matrix = np.zeros((row - 1, col, 2), dtype=np.int32) top_matrix = np.zeros((row, col - 1, 2), dtype=np.int32) # 计算纵向配准 for i in range(row): for j in range(col - 1): print(f"{i}-{j}.jpg and {i}-{j + 1}.jpg") dx, dy = tb_match(f"cell/{i}-{j}.jpg", f"cell/{i}-{j + 1}.jpg") top_matrix[i, j] = dx, dy print(top_matrix) # 计算横向配准 for j in range(col): for i in range(row - 1): print(f"{i}-{j}.jpg and {i + 1}-{j}.jpg") dx, dy = lr_match(f"cell/{i}-{j}.jpg", f"cell/{i + 1}-{j}.jpg") left_matrix[i, j] = dx, dy print(left_matrix)