OpenCV 基于SIFT的特征匹配

import cv2


'''
src_img: source pic
dst_img: target pic
dst_img_set: target pic set
src_coor: (src_x, src_y, src_w, src_h)
dst_coor: (dst_x, dst_y, dst_w, dst_h)
dst_img_set: [(dst_x1, dst_y1, dst_w1, dst_h1), (dst_x2, dst_y2, dst_w2, dst_h2), ...]
'''
def get_feature_matched(src_coor, src_img, dst_coor, dst_img_set):
	img_frame1 = cv2.imread(src_img,cv2.IMREAD_GRAYSCALE)
    img_frame1 = img_frame1[src_coor[1]: src_coor[1] + src_coor[3], src_coor[0]: src_coor[0] + src_coor[2]]
    
	sift = cv2.xfeatures2d.SIFT_create()
    kp1, des1 = sift.detectAndCompute(img_frame1, None)
    bf = cv2.BFMatcher()
    All_set = {}

    for dst_img in dst_img_set:
	    img_frame2 = cv2.imread(img2,cv2.IMREAD_GRAYSCALE)
	    tmp_img_frame2 = img_frame2.copy()
	    tmp_img_frame2 = tmp_img_frame2[detection_y: detection_y + detection_h, detection_x: detection_x + detection_w]
	    kp2, des2 = sift.detectAndCompute(tmp_img_frame2, None)
	    matches = bf.knnMatch(des1, des2, k=2)
	    good = []
	    for m, n in matches:
	        if m.distance < 0.75 * n.distance:
	            good.append([m])
	    All_set[len(good)] = dst_coor
	tmp = []
	for x in All_set.keys()
		tmp.append(x)
	best = max(tmp)
	best_coor = All_set.get(best)
	return best_coor


if __name__ == '__main__':
	src_img = ''
	src_coor = (x0, y0, w0, h0)
	dst_img = ''
	dst_img_set = [(x1, y1, w1, h1), (x2, y2, w2, h2)]
	target_coor = get_feature_matched(src_img, src_coor, dst_img, dst_img_set)



发布了11 篇原创文章 · 获赞 0 · 访问量 559

猜你喜欢

转载自blog.csdn.net/leo19930725/article/details/105466939
今日推荐