Python實現(xiàn)圖像的全景拼接
基本介紹
圖像的全景拼接,即“縫合”兩張具有重疊區(qū)域的圖來創(chuàng)建一張全景圖。其中用到了計算機視覺和圖像處理技術(shù)有:關(guān)鍵點特征檢測、局部不變特征、關(guān)鍵特征點匹配、RANSAC(Random Sample Consensus,隨機采樣一致性)和透視變形。
具體步驟
(1)檢測左右兩張圖像的SIFT關(guān)鍵特征點,并提取局部不變特征 ;
(2)使用knnMatch檢測來自右圖(左圖)的SIFT特征,與左圖(右圖)進行匹配 ;
(3)計算視角變換矩陣H,用變換矩陣H對右圖進行扭曲變換;
(4)將左圖(右圖)加入到變換后的圖像的左側(cè)(右側(cè))獲得最終圖像;
代碼:
- import cv2 as cv # 導(dǎo)入opencv包
- import numpy as np # 導(dǎo)入numpy包,圖像處理中的矩陣運算需要用到
- # 檢測圖像的SIFT關(guān)鍵特征點
- def sift_keypoints_detect(image):
- # 處理圖像一般很少用到彩色信息,通常直接將圖像轉(zhuǎn)換為灰度圖
- gray_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
- # 獲取圖像特征sift-SIFT特征點,實例化對象sift
- sift = cv.xfeatures2d.SIFT_create()
- # keypoints:特征點向量,向量內(nèi)的每一個元素是一個KeyPoint對象,包含了特征點的各種屬性信息(角度、關(guān)鍵特征點坐標(biāo)等)
- # features:表示輸出的sift特征向量,通常是128維的
- keypoints, features = sift.detectAndCompute(image, None)
- # cv.drawKeyPoints():在圖像的關(guān)鍵特征點部位繪制一個小圓圈
- # 如果傳遞標(biāo)志flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS,它將繪制一個大小為keypoint的圓圈并顯示它的方向
- # 這種方法同時顯示圖像的坐標(biāo),大小和方向,是最能顯示特征的一種繪制方式
- keypoints_image = cv.drawKeypoints(
- gray_image, keypoints, None, flags=cv.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS)
- # 返回帶關(guān)鍵特征點的圖像、關(guān)鍵特征點和sift的特征向量
- return keypoints_image, keypoints, features
- # 使用KNN檢測來自左右圖像的SIFT特征,隨后進行匹配
- def get_feature_point_ensemble(features_right, features_left):
- # 創(chuàng)建BFMatcher對象解決匹配
- bf = cv.BFMatcher()
- # knnMatch()函數(shù):返回每個特征點的最佳匹配k個匹配點
- # features_right為模板圖,features_left為匹配圖
- matches = bf.knnMatch(features_right, features_left, k=2)
- # 利用sorted()函數(shù)對matches對象進行升序(默認(rèn))操作
- matches = sorted(matches, key=lambda x: x[0].distance / x[1].distance)
- # x:x[]字母可以隨意修改,排序方式按照中括號[]里面的維度進行排序,[0]按照第一維排序,[2]按照第三維排序
- # 建立列表good用于存儲匹配的點集
- good = []
- for m, n in matches:
- # ratio的值越大,匹配的線條越密集,但錯誤匹配點也會增多
- ratio = 0.6
- if m.distance < ratio * n.distance:
- good.append(m)
- # 返回匹配的關(guān)鍵特征點集
- return good
- # 計算視角變換矩陣H,用H對右圖進行變換并返回全景拼接圖像
- def Panorama_stitching(image_right, image_left):
- _, keypoints_right, features_right = sift_keypoints_detect(image_right)
- _, keypoints_left, features_left = sift_keypoints_detect(image_left)
- goodMatch = get_feature_point_ensemble(features_right, features_left)
- # 當(dāng)篩選項的匹配對大于4對(因為homography單應(yīng)性矩陣的計算需要至少四個點)時,計算視角變換矩陣
- if len(goodMatch) > 4:
- # 獲取匹配對的點坐標(biāo)
- ptsR = np.float32(
- [keypoints_right[m.queryIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
- ptsL = np.float32(
- [keypoints_left[m.trainIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
- # ransacReprojThreshold:將點對視為內(nèi)點的最大允許重投影錯誤閾值(僅用于RANSAC和RHO方法時),若srcPoints和dstPoints是以像素為單位的,該參數(shù)通常設(shè)置在1到10的范圍內(nèi)
- ransacReprojThreshold = 4
- # cv.findHomography():計算多個二維點對之間的最優(yōu)單映射變換矩陣 H(3行x3列),使用最小均方誤差或者RANSAC方法
- # 函數(shù)作用:利用基于RANSAC的魯棒算法選擇最優(yōu)的四組配對點,再計算轉(zhuǎn)換矩陣H(3*3)并返回,以便于反向投影錯誤率達到最小
- Homography, status = cv.findHomography(
- ptsR, ptsL, cv.RANSAC, ransacReprojThreshold)
- # cv.warpPerspective():透視變換函數(shù),用于解決cv2.warpAffine()不能處理視場和圖像不平行的問題
- # 作用:就是對圖像進行透視變換,可保持直線不變形,但是平行線可能不再平行
- Panorama = cv.warpPerspective(
- image_right, Homography, (image_right.shape[1] + image_left.shape[1], image_right.shape[0]))
- cv.imshow("扭曲變換后的右圖", Panorama)
- cv.waitKey(0)
- cv.destroyAllWindows()
- # 將左圖加入到變換后的右圖像的左端即獲得最終圖像
- Panorama[0:image_left.shape[0], 0:image_left.shape[1]] = image_left
- # 返回全景拼接的圖像
- return Panorama
- if __name__ == '__main__':
- # 讀取需要拼接的圖像,需要注意圖像左右的順序
- image_left = cv.imread("./Left.jpg")
- image_right = cv.imread("./Right.jpg")
- # 通過調(diào)用cv2.resize()使用插值的方式來改變圖像的尺寸,保證左右兩張圖像大小一致
- # cv.resize()函數(shù)中的第二個形參dsize表示輸出圖像大小尺寸,當(dāng)設(shè)置為0(None)時,則表示按fx與fy與原始圖像大小相乘得到輸出圖像尺寸大小
- image_right = cv.resize(image_right, None, fx=0.4, fy=0.24)
- image_left = cv.resize(image_left, (image_right.shape[1], image_right.shape[0]))
- # 獲取檢測到關(guān)鍵特征點后的圖像的相關(guān)參數(shù)
- keypoints_image_right, keypoints_right, features_right = sift_keypoints_detect(image_right)
- keypoints_image_left, keypoints_left, features_left = sift_keypoints_detect(image_left)
- # 利用np.hstack()函數(shù)同時將原圖和繪有關(guān)鍵特征點的圖像沿著豎直方向(水平順序)堆疊起來
- cv.imshow("左圖關(guān)鍵特征點檢測", np.hstack((image_left, keypoints_image_left)))
- # 一般在imshow后設(shè)置 waitKey(0) , 代表按任意鍵繼續(xù)
- cv.waitKey(0)
- # 刪除先前建立的窗口
- cv.destroyAllWindows()
- cv.imshow("右圖關(guān)鍵特征點檢測", np.hstack((image_right, keypoints_image_right)))
- cv.waitKey(0)
- cv.destroyAllWindows()
- goodMatch = get_feature_point_ensemble(features_right, features_left)
- # cv.drawMatches():在提取兩幅圖像特征之后,畫出匹配點對連線
- # matchColor – 匹配的顏色(特征點和連線),若matchColor==Scalar::all(-1),顏色隨機
- all_goodmatch_image = cv.drawMatches(
- image_right, keypoints_right, image_left, keypoints_left, goodMatch, None, None, None, None, flags=2)
- cv.imshow("所有匹配的SIFT關(guān)鍵特征點連線", all_goodmatch_image)
- cv.waitKey(0)
- cv.destroyAllWindows()
- # 把圖片拼接成全景圖并保存
- Panorama = Panorama_stitching(image_right, image_left)
- cv.namedWindow("全景圖", cv.WINDOW_AUTOSIZE)
- cv.imshow("全景圖", Panorama)
- cv.imwrite("./全景圖.jpg", Panorama)
- cv.waitKey(0)
- cv.destroyAllWindows()
左圖關(guān)鍵特征點檢測
右圖關(guān)鍵特征點檢測
所有匹配的SIFT關(guān)鍵特征點連線
扭曲變換后的右圖
全景圖
由于輸入的左右圖像之間有大量重疊,導(dǎo)致全景圖的主要添加部分是在拼接圖像的右側(cè),因此會造成拼接后全景圖右側(cè)有大量的黑色空白區(qū)域。