opencv-图像融合拼接

带拼接图片

在这里插入图片描述
在这里插入图片描述

基于SIFT特征点和RANSAC方法得到的图像特征点匹配结果

在这里插入图片描述

图像变换结果

在这里插入图片描述

完整代码

# 读取图像
import cv2 #opencv读取的格式是BGR
import matplotlib.pyplot as plt
import numpy as np 


img=cv2.imread('right.jpg')
img2=cv2.imread('left.jpg')

def detectAndCompute(image):

    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    sift = cv2.xfeatures2d.SIFT_create()

    (kps, features) = sift.detectAndCompute(image, None)

    kps = np.float32([kp.pt for kp in kps]) # 得到的点需要进一步转换才能使用

    return (kps, features)
def matchKeyPoints(kpsA, kpsB, featuresA, featuresB, ratio = 0.75, reprojThresh = 4.0):
     # ratio是最近邻匹配的推荐阈值
     # reprojThresh是随机取样一致性的推荐阈值
     matcher = cv2.BFMatcher()
     rawMatches = matcher.knnMatch(featuresA, featuresB, 2)
     matches = []
     for m in rawMatches:
         if len(m) == 2 and m[0].distance < ratio * m[1].distance:
            matches.append((m[0].queryIdx, m[0].trainIdx))
     kpsA = np.float32([kpsA[m[0]] for m in matches]) # 使用np.float32转化列表
     kpsB = np.float32([kpsB[m[1]] for m in matches])
     (M, status) = cv2.findHomography(kpsA, kpsB, cv2.RANSAC, reprojThresh)
     return (M, matches, status) # 并不是所有的点都有匹配解,它们的状态存在status中

def stich(imgA, imgB, M):

    result = cv2.warpPerspective(imgA, M, (imgA.shape[1] + imgB.shape[1], imgA.shape[0]))

    result[0:imgA.shape[0], 0:imgB.shape[1]] = imgB
    cv_show('result', result)

def drawMatches(imgA, imgB, kpsA, kpsB, matches, status):
     (hA, wA) = imgA.shape[0:2]
     (hB, wB) = imgB.shape[0:2]
     # 注意这里的3通道和uint8类型
     drawImg = np.zeros((max(hA, hB), wA + wB, 3), 'uint8')
     drawImg[0:hB, 0:wB] = imgB
     drawImg[0:hA, wB:] = imgA
     for ((queryIdx, trainIdx),s) in zip(matches, status):
         if s == 1:
             # 注意将float32 --> int
             pt1 = (int(kpsB[trainIdx][0]), int(kpsB[trainIdx][1]))
             pt2 = (int(kpsA[trainIdx][0]) + wB, int(kpsA[trainIdx][1]))
             cv2.line(drawImg, pt1, pt2, (0, 0, 255))
     cv_show("drawImg", drawImg)

#图像的显示,也可以创建多个窗口
def cv_show(name,img):
    cv2.imshow(name,img) 
    # 等待时间,毫秒级,0表示任意键终止
    cv2.waitKey(0) 
    cv2.destroyAllWindows()
(kpsA, featuresA) = detectAndCompute(img)

(kpsB, featuresB) = detectAndCompute(img2)

(M, matches, status) = matchKeyPoints(kpsA, kpsB, featuresA, featuresB)

# 绘制匹配结果
drawMatches(img, img2, kpsA, kpsB, matches, status)

stich(img, img2, M)
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tc.小浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值