python實(shí)現(xiàn)圖像拼接
本文實(shí)例為大家分享了python實(shí)現(xiàn)圖像拼接的具體代碼,供大家參考,具體內(nèi)容如下
1.待拼接的圖像
2. 基于SIFT特征點(diǎn)和RANSAC方法得到的圖像特征點(diǎn)匹配結(jié)果
3.圖像變換結(jié)果
4.代碼及注意事項(xiàng)
import cv2import numpy as np def cv_show(name, image): cv2.imshow(name, image) cv2.waitKey(0) cv2.destroyAllWindows() 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]) # 得到的點(diǎn)需要進(jìn)一步轉(zhuǎn)換才能使用 return (kps, features) def matchKeyPoints(kpsA, kpsB, featuresA, featuresB, ratio = 0.75, reprojThresh = 4.0): # ratio是最近鄰匹配的推薦閾值 # reprojThresh是隨機(jī)取樣一致性的推薦閾值 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轉(zhuǎn)化列表 kpsB = np.float32([kpsB[m[1]] for m in matches]) (M, status) = cv2.findHomography(kpsA, kpsB, cv2.RANSAC, reprojThresh) return (M, matches, status) # 并不是所有的點(diǎn)都有匹配解,它們的狀態(tài)存在status中 def stich(imgA, imgB, M): result = cv2.warpPerspective(imgA, M, (imgA.shape[1] + imgB.shape[1], imgA.shape[0])) result[0:imageA.shape[0], 0:imageB.shape[1]] = imageB 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] = imageB drawImg[0:hA, wB:] = imageA 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) # 讀取圖像imageA = cv2.imread(’./right_01.png’)cv_show('imageA', imageA)imageB = cv2.imread(’./left_01.png’)cv_show('imageB', imageB)# 計(jì)算SIFT特征點(diǎn)和特征向量(kpsA, featuresA) = detectAndCompute(imageA)(kpsB, featuresB) = detectAndCompute(imageB)# 基于最近鄰和隨機(jī)取樣一致性得到一個(gè)單應(yīng)性矩陣(M, matches, status) = matchKeyPoints(kpsA, kpsB, featuresA, featuresB)# 繪制匹配結(jié)果drawMatches(imageA, imageB, kpsA, kpsB, matches, status)# 拼接stich(imageA, imageB, M)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 解決Android Studio 格式化 Format代碼快捷鍵問(wèn)題2. php解決注冊(cè)并發(fā)問(wèn)題并提高QPS3. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問(wèn)題4. 在Chrome DevTools中調(diào)試JavaScript的實(shí)現(xiàn)5. Springboot 全局日期格式化處理的實(shí)現(xiàn)6. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)7. Java使用Tesseract-Ocr識(shí)別數(shù)字8. vue實(shí)現(xiàn)web在線聊天功能9. JAMon(Java Application Monitor)備忘記10. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼
