StitchingCodes/two-stitching-tb.py
2025-06-08 20:21:47 +08:00

71 lines
2.1 KiB
Python

import cv2
import numpy as np
from matplotlib import pyplot as plt
if __name__ == "__main__":
top_img = cv2.imread("top.jpg")
bottom_img = cv2.imread("bottom.jpg")
# 配准
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}")
# 拼接
new_h, new_w = h + dy, w + abs(dx)
canvas = np.zeros((new_h, new_w, 3), dtype=np.uint8)
top_mask = np.zeros((new_h, new_w), dtype=np.uint8)
bottom_mask = np.zeros((new_h, new_w), dtype=np.uint8)
iou = np.zeros((new_h, new_w), dtype=np.uint8)
if dx >= 0:
canvas[0:h, 0:w] = top_img
canvas[dy:new_h, dx:new_w] = bottom_img
top_mask[0:h, 0:w] = 255
bottom_mask[dy:new_h, dx:new_w] = 255
iou = cv2.bitwise_and(top_mask, bottom_mask)
else:
dx = -dx
canvas[0:h, dx:new_w] = top_img
canvas[dy:new_h, 0:w] = bottom_img
top_mask[0:h, dx:new_w] = 255
bottom_mask[dy:new_h, 0:w] = 255
iou = cv2.bitwise_and(top_mask, bottom_mask)
plt.subplot(221)
plt.imshow(cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB))
plt.subplot(222)
plt.imshow(iou, cmap='hot')
plt.subplot(223)
plt.imshow(top_mask, cmap='hot')
plt.subplot(224)
plt.imshow(bottom_mask, cmap='hot')
plt.show()
cv2.imwrite("stitching-tb.jpg", canvas)