实现两张图片的接缝线拼接

发布时间:2023年12月20日

使用ORB算法检测特征点,并通过BFMatcher进行特征点匹配。然后,根据Lowe's ratio test选择好的匹配点,并使用findHomography计算单应性矩阵。最后,使用warpPerspective将图像进行透视变换,然后将第二张图像粘贴到变换后的图像上。

import cv2
import numpy as np

def find_homography_and_blend(image1, image2, output_path):
    # 读取两张图片
    img1 = cv2.imread(image1)
    img2 = cv2.imread(image2)

    # 转换为灰度图像
    gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

    # 使用ORB算法检测特征点
    orb = cv2.ORB_create()
    keypoints1, descriptors1 = orb.detectAndCompute(gray1, None)
    keypoints2, descriptors2 = orb.detectAndCompute(gray2, None)

    # 使用BFMatcher进行特征点匹配
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(descriptors1, descriptors2, k=2)

    # 根据Lowe's ratio test选择好的匹配点
    good_matches = []
    for m, n in matches:
        if m.distance < 0.75 * n.distance:
            good_matches.append(m)

    # 获取匹配点的坐标
    src_pts = np.float32([keypoints1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
    dst_pts = np.float32([keypoints2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)

    # 使用findHomography计算单应性矩阵
    homography, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)

    # 使用warpPerspective将图像进行透视变换
    result = cv2.warpPerspective(img1, homography, (img1.shape[1] + img2.shape[1], img1.shape[0]))

    # 将第二张图像粘贴到变换后的图像上
    result[0:img2.shape[0], 0:img2.shape[1]] = img2

    # 保存融合后的图像
    cv2.imwrite(output_path, result)

# 设置两张图片的路径和融合后的输出路径
image_path1 = "path/to/image1.jpg"
image_path2 = "path/to/image2.jpg"
output_path = "path/to/output.jpg"

# 调用融合函数
find_homography_and_blend(image_path1, image_path2, output_path)

文章来源:https://blog.csdn.net/weixin_57111012/article/details/135035152
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。