python - 为什么 Homography 不在检测到的对象上绘制框?
问题描述
我使用一些 OpenCV 教程中的代码来检测基于 SIFT 特征的对象。使用教程中的图像时效果很好,但是当我使用自己的图像集时它似乎关闭了。
import numpy as np
import cv2
from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 10
img1 = cv2.imread('img1.jpg',0) # queryImage
img2 = cv2.imread('img2.jpg',0) # trainImage
# Initiate SIFT detector
sift = cv2.xfeatures2d.SIFT_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
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)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.3*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)
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)
img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA)
else:
print("Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT))
matchesMask = None
draw_params = dict(matchColor = (0,0,255), # draw matches in green color
singlePointColor = None,
matchesMask = matchesMask, # draw only inliers
flags = 2)
img3 = cv2.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)
#img3 = cv2.resize(img3, None, fx=0.25, fy=0.25)
cv2.imshow("Result", img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
解决方案
推荐阅读
- javascript - 在 PHP 中使用 JS 更改类属性
- d3.js - 了解访问函数 (d)
- sql - Postgresql:按 OR 条件选择行 - 包括通过 json 数组
- c++ - 无法在 C++ for 循环中更新两个变量
- asp.net - SignalR如何取消绑定方法侦听器
- c# - 在 C# 中的 Model 类中处理 HttpClient 的最佳方法
- node.js - 我怎样才能创建一个可读的管道到一个可写的,这将允许我不时向它添加内容?
- python-3.x - 为背包问题中选择的最小对象数创建约束
- c++ - 我可以为类类型重载 << 运算符以在 C++ 中生成文本和二进制文件,同时能够链接 << 操作吗?
- javascript - 为什么当我复制变量时不起作用