컴퓨터 비젼(Computer Vision)/특징점 검출과 매칭
좋은 매칭 선별
rongxian
2022. 2. 22. 15:22
선별 방법 1.
가장 좋은 매칭 결과에서 distance 값이 작은 것 N개를 사용
cv2.DMatch.distance 값을 기준으로 정렬 후 상위 N개 선별
...
matcher = cv2.BFMatcher_create()
matches = matcher.match(desc1, desc2)
# 좋은 매칭 결과 선별
matches = sorted(matches, key=labmda i: i.distance) # 거리별 오름차순 정렬
good_matches = matches[:80] # 상위 80개만 선별
# 특징점 매칭 결과 영상 생성
dst = cv2.drawMatches(src1, kp1, src2, kp2, good_matchers, None)
...
선별 방법 2. (SIFT에서 제안된 방법)
가장 좋은 매칭 결과의 distance 값과 두 번째로 좋은 매칭 결과의 distance 값의 비율을 계산
이 비율이 임계값(예를들어 0.7)보다 작으면 선택
...
# 특징점 매칭
matcher = cv2.BFMatcher_create()
matches = matcher.knnMatch(desc1, desc2, 2) # knnMatcher를 쓰고 3번째 paramter가 2임을 확인
# 좋은 매칭 결과 선별
good_matches = []
for m in matches:
if m[0].distance / m[1].distance < 0.7:
# closest_distance / next_cloest_distnace < Th
good_matches.append(m[0])
dst = cv2.drawMatchers(src1, kp1, src2, kp2, good_matches, None)
...
예시
코드
import sys
import cv2
# 영상 불러오기
src1 = cv2.imread('graf1.png', cv2.IMREAD_GRAYSCALE)
src2 = cv2.imread('graf3.png', cv2.IMREAD_GRAYSCALE)
if src1 is None or src2 is None:
print('Image load failed!')
sys.exit()
# 특징점 알고리즘 객체 생성 (KAZE, AKAZE, ORB 등)
feature = cv2.KAZE_create() # 실수 기술자
#feature = cv2.AKAZE_create() # 이진 기술자
#feature = cv2.ORB_create() # 이진 기술자
# 특징점 검출 및 기술자 계산
kp1, desc1 = feature.detectAndCompute(src1, None)
kp2, desc2 = feature.detectAndCompute(src2, None)
# 특징점 매칭
matcher = cv2.BFMatcher_create()
#matcher = cv2.BFMatcher_create(cv2.NORM_HAMMING)
matches = matcher.knnMatch(desc1, desc2, 2)
# 좋은 매칭 결과 선별
th = 0.7
good_matches = []
for m in matches:
if m[0].distance / m[1].distance < th:
good_matches.append(m[0])
print('# of kp1:', len(kp1))
print('# of kp2:', len(kp2))
print('# of matches:', len(matches))
print('# of good_matches:', len(good_matches))
# 특징점 매칭 결과 영상 생성
dst = cv2.drawMatches(src1, kp1, src2, kp2, good_matches, None)
cv2.imshow('dst', dst)
cv2.waitKey()
cv2.destroyAllWindows()
결과
# of kp1: 3159
# of kp2: 3625
# of matches: 3159
# of good_matches: 384