计算机视觉:全景拼接(Panorama Stitching)

计算机视觉:全景拼接(Panorama Stitching)

  • 原理
  • 环境
  • 代码
  • 示例

原理

全景拼接是将多幅图像拼接成一幅大尺度图像。同一个相机拍摄空间同一平面的两张图像,这两张图像之间的映射关系可以用投影(透视)变换矩阵(homography矩阵)表示。

基本原理如下:我们假定只包含两个图像,且图像以从左到右的顺序提供。首先读取图像列表,我们使用高斯差分(DoG)关键点检测器和SIFT特征描述子,得到关键点和特征,通过K邻近算法进行特征匹配,并对原始匹配点进行Lowe比率测试,然后依据至少四个匹配的关键点使用RANSAC算法估计投影变换矩阵,最终将图像经投影变换进行拼接生成全景图。

其中,RANSAC(Random Sample Consensus)即随机采样一致性,该方法是用来找到正确模型来拟合带有噪声数据的迭代方法。RANSAC的基本思想在于,找到正确数据点的同时摒弃噪声点。

环境

  • python == 3.7
  • numpy == 1.21.6
  • opencv-python == 3.4.2.17
  • opencv-contrib-python == 3.4.2.17
  • imutils == 0.5.4

代码

# USAGE
# python stitch.py --first images/imageA.png --second images/imageB.png 

# import the necessary packages
from panorama import Stitcher
import argparse
import imutils
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--first", required=True,
	help="path to the first image")
ap.add_argument("-s", "--second", required=True,
	help="path to the second image")
args = vars(ap.parse_args())

# load the two images and resize them to have a width of 400 pixels
# (for faster processing)
imageA = cv2.imread(args["first"])
imageB = cv2.imread(args["second"])
imageA = imutils.resize(imageA, width=400)
imageB = imutils.resize(imageB, width=400)

# stitch the images together to create a panorama
stitcher = Stitcher()
(result, vis) = stitcher.stitch([imageA, imageB], showMatches=True)

# show the images
cv2.imshow("Image A", imageA)
cv2.imshow("Image B", imageB)
cv2.imshow("Keypoint Matches", vis)
cv2.imshow("Result", result)
cv2.waitKey(0)
# import the necessary packages
import numpy as np
import imutils
import cv2

class Stitcher:
	def __init__(self):
		# determine if we are using OpenCV v3.X
		self.isv3 = imutils.is_cv3()

	def stitch(self, images, ratio=0.75, reprojThresh=4.0,
		showMatches=False):
		# unpack the images, then detect keypoints and extract
		# local invariant descriptors from them
		(imageB, imageA) = images
		(kpsA, featuresA) = self.detectAndDescribe(imageA)
		(kpsB, featuresB) = self.detectAndDescribe(imageB)

		# match features between the two images
		M = self.matchKeypoints(kpsA, kpsB,
			featuresA, featuresB, ratio, reprojThresh)

		# if the match is None, then there aren't enough matched
		# keypoints to create a panorama
		if M is None:
			return None

		# otherwise, apply a perspective warp to stitch the images together
		(matches, H, status) = M
		result = cv2.warpPerspective(imageA, H,
			(imageA.shape[1] + imageB.shape[1], imageA.shape[0]))
		result[0:imageB.shape[0], 0:imageB.shape[1]] = imageB

		# check to see if the keypoint matches should be visualized
		if showMatches:
			vis = self.drawMatches(imageA, imageB, kpsA, kpsB, matches,
				status)

			# return a tuple of the stitched image and the visualization
			return (result, vis)

		# return the stitched image
		return result

	def detectAndDescribe(self, image):
		# convert the image to grayscale
		gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
		
		# detect and extract features from the image
		# FAST and BRIEF
		# Initiate FAST detector
		# fast = cv2.xfeatures2d.StarDetector_create()
		# Initiate BRIEF extractor
		# brief = cv2.xfeatures2d.BriefDescriptorExtractor_create()
		# find the keypoints with STAR
		# kp = fast.detect(img,None)
		# compute the descriptors with BRIEF
		# (kps, features) = brief.compute(img, kp)
		# SIFT
		descriptor = cv2.xfeatures2d.SIFT_create()
		# SURF
		# descriptor = cv2.xfeatures2d.SURF_create()
		(kps, features) = descriptor.detectAndCompute(image, None)

		# convert the keypoints from KeyPoint objects to NumPy arrays
		kps = np.float32([kp.pt for kp in kps])

		# return a tuple of keypoints and features
		return (kps, features)

	def matchKeypoints(self, kpsA, kpsB, featuresA, featuresB,
		ratio, reprojThresh):
		# compute the raw matches and initialize the list of actual matches
		matcher = cv2.DescriptorMatcher_create("BruteForce")
		rawMatches = matcher.knnMatch(featuresA, featuresB, 2)
		matches = []

		# loop over the raw matches
		for m in rawMatches:
			# ensure the distance is within a certain ratio of each other
			# (i.e. Lowe's ratio test)
			if len(m) == 2 and m[0].distance < m[1].distance * ratio:
				matches.append((m[0].trainIdx, m[0].queryIdx))

		# computing a homography requires at least 4 matches
		if len(matches) > 4:
			# construct the two sets of points
			ptsA = np.float32([kpsA[i] for (_, i) in matches])
			ptsB = np.float32([kpsB[i] for (i, _) in matches])

			# compute the homography between the two sets of points
			(H, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC,
				reprojThresh)

			# return the matches along with the homograpy matrix
			# and status of each matched point
			return (matches, H, status)

		# otherwise, no homograpy could be computed
		return None

	def drawMatches(self, imageA, imageB, kpsA, kpsB, matches, status):
		# initialize the output visualization image
		(hA, wA) = imageA.shape[:2]
		(hB, wB) = imageB.shape[:2]
		vis = np.zeros((max(hA, hB), wA + wB, 3), dtype="uint8")
		vis[0:hA, 0:wA] = imageA
		vis[0:hB, wA:] = imageB

		# loop over the matches
		for ((trainIdx, queryIdx), s) in zip(matches, status):
			# only process the match if the keypoint was successfully matched
			if s == 1:
				# draw the match
				ptA = (int(kpsA[queryIdx][0]), int(kpsA[queryIdx][1]))
				ptB = (int(kpsB[trainIdx][0]) + wA, int(kpsB[trainIdx][1]))
				cv2.line(vis, ptA, ptB, (0, 255, 0), 1)

		# return the visualization
		return vis

示例

原始图片A:

原始图片B:

关键点匹配:
计算机视觉:全景拼接(Panorama Stitching)_第1张图片
全景拼接:
计算机视觉:全景拼接(Panorama Stitching)_第2张图片
由此图可见,左图为原始图像,右图为经投影变换后的图像。

你可能感兴趣的:(计算机视觉,计算机视觉,python,opencv)