您的位置:首页 > 编程语言 > Python开发

python+opencv目标匹配技术

2016-04-10 22:34 585 查看
先上两个code吧

#!/usr/bin/env python

import cv2
import numpy as np

img1 = cv2.imread('box.png', 0)
img2 = cv2.imread('box_in_scene.png', 0)

orb = cv2.ORB_create()

kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)

bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

matches = bf.match(des1, des2)

matches = sorted(matches, key = lambda x:x.distance)

img3 = np.zeros((720, 1280, 3), np.uint8)
#img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], img3, (255,0,0), (0,255,255), None, 2)
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], img3)

cv2.imshow('match', img3)
cv2.waitKey(0)

利用透视变换技术进行匹配

#!/usr/bin/env python

import cv2
import numpy as np
from matplotlib import pyplot as plt

MIN_MATCH_COUNT = 10

img1 = cv2.imread('box.png', 0)
img2 = cv2.imread('box_in_scene.png', 0)

orb = cv2.ORB_create()

kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)

if True:
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)

flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
else:
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)

matches = sorted(matches, key = lambda x:x.distance)
print 'matches shape:',matches

good = []
for m,n in matches:
if m.distance < 0.7 * n.disance:
good.append(m)

if len(good) > MIN_MATCH_COUNT:
src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1,1,2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1,1,2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
print 'transform Martix:', M
matchesMask = mask.ravel().tolist()

h,w = img1.shape
pts = np.float32([[0,0],[0,h-1],[w-1,h-1],[w-1,0]]).reshape(-1,1,2)
dst = cv2.perspectiveTransform(pts, M)
cv2.polylines(img2, [np.int32(dst)], True,255,10,cv2.LINE_AA)
else:
print "Not enough matches are fond-%d/%d"% (len(good), MIN_MATCH_COUNT)
matchesMask = None

draw_params = dict(matchColor=(0,255,0),
singlePointColor=None,
matchesMask = matchesMask,
flag2 = 2)

img3 = cv2.drawMatches(img1, kp1, img2, kp2, good, None, **draw_params)

cv2.imshow('match', img3)
cv2.waitKey(0)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: