特徴マッチングによる物体検知

2019/09/04

Python2.7.8, OpenCV4.1.1

# -*- coding: utf-8 -*-
import numpy as np
import cv2

MIN_MATCH_COUNT = 4

img1 = cv2.imread('box.png', 0)  # queryImage
img2 = cv2.imread('box_in_scene.png', 0) # trainImage
img2c = cv2.imread('box_in_scene.png')

detector = cv2.AKAZE_create()
kp1, des1 = detector.detectAndCompute(img1, None)
kp2, des2 = detector.detectAndCompute(img2, None)

bf = cv2.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)

good = []
for m,n in matches:
    if m.distance < 0.7*n.distance:
        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)

    if M is None:
        print ('No Homography')
    else:
        print ('Find Homography')
        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)

        img2c = cv2.polylines(img2c,[np.int32(dst)],True,(0,0,255),2,cv2.LINE_AA)

else:
    print ('Not enough matches are found - %d/%d' % (len(good),MIN_MATCH_COUNT))
    matchesMask = None

draw_params = dict(matchColor = (0,255,0), # draw matches in green color
                   singlePointColor = None,
                   matchesMask = matchesMask, # draw only inliers
                   flags = 2)

img3 = cv2.drawMatches(img1,kp1,img2c,kp2,good,None,**draw_params)
cv2.imwrite('result_box_in_scene.png', img3)

cv2.namedWindow('Result', cv2.WINDOW_KEEPRATIO | cv2.WINDOW_NORMAL)
cv2.imshow('Result', img3)
cv2.waitKey(0)


実行結果

素材画像 box.png  box_in_scene.png

特徴点のマッチングとHomographyによる物体検出
http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_feature2d/py_feature_homography/py_feature_homography.html