我将演示如何使用Python和OpenCV执行图像拼接和全景图构建。给定两个图像,我们将它们“拼接”在一起以创建一个简单的全景图,如上面的示例所示。 要构建图像全景图…
需要注意,由于本次实验需要使用到SIFT这种非自由专利算法,而在2020年3月5日之前该专利算法是不能通过pip工具安装的opencv-python和opencv-contrib-python使用的,但是在2020年3月5日之后该专利就到期了。可以通过使用新版本的python,然后搭配pip工具安装最新的opencv-python和opencv-contrib-python,从而使用SIFT这种非自由专利算法!
我们的全景拼接算法将包含以下四个步骤
Step #1:检测关键点(DoG,Harris等),并从两个输入图像中提取局部不变描述符(SIFT,SURF等)。
Step #2:在两个图像之间匹配描述符。
Step #3:使用RANSAC算法通过匹配的特征向量估计单应矩阵(或者叫变换矩阵)(homography matrix )。
Step #4:用 step #3 中的单应矩阵进行透视变换
我们将所有这四个步骤封装在Panorama.py中,接着在其中定义用于构建全景图的Stitcher类。
Stitcher类将依赖于imutils Python软件包,因此,如果你尚未在系统上安装该软件包,则要立即进行操作:
pip install imutils
# 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(or_better=True)
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)
# check to see if we are using OpenCV 3.X
if self.isv3:
# detect and extract features from the image
# descriptor = cv2.xfeatures2d.SIFT_create()
descriptor = cv2.SIFT_create()
(kps, features) = descriptor.detectAndCompute(image, None)
# otherwise, we are using OpenCV 2.4.X
else:
# detect keypoints in the image
detector = cv2.FeatureDetector_create("SIFT")
kps = detector.detect(gray)
# extract features from the image
extractor = cv2.DescriptorExtractor_create("SIFT")
(kps, features) = extractor.compute(gray, kps)
# 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
可能遇到的报错
Traceback (most recent call last):
File "C:\Users\HP\Downloads\panorama_pyimagesearch-main\stitch.py", line 23, in <module>
(result, vis) = stitcher.stitch([imageA, imageB], showMatches=True)
File "C:\Users\HP\Downloads\panorama_pyimagesearch-main\pyimagesearch\panorama.py", line 17, in stitch
(kpsA, featuresA) = self.detectAndDescribe(imageA)
File "C:\Users\HP\Downloads\panorama_pyimagesearch-main\pyimagesearch\panorama.py", line 49, in detectAndDescribe
descriptor = cv2.xfeatures2d.SIFT_create()
AttributeError: module 'cv2' has no attribute 'xfeatures2d'
修改:
# descriptor = cv2.xfeatures2d.SIFT_create()
descriptor = cv2.SIFT_create()
# import the necessary packages
from pyimagesearch.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)
# panorama_pyimagesearch
# 简单地拼接两幅全景地图用法:
python stitch.py --first bryce_01.png --second bryce_02.png
以上是基于图片的拼接,最终我会生成一个基于多路摄像头的全景视频。 敬请期待