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