参考博客
https://blog.csdn.net/Eddy_zheng/article/details/78916009
前提准备
pip install imagedt
运行代码:
# coding: utf-8
from matplotlib import pyplot as plt
from imagedt.decorator import time_cost
import cv2
print 'cv version: ', cv2.__version__
def bgr_rgb(img):
(r, g, b) = cv2.split(img)
return cv2.merge([b, g, r])
def orb_detect(image_a, image_b):
# feature match
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(image_a, None)
kp2, des2 = orb.detectAndCompute(image_b, None)
# create BFMatcher object
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# Match descriptors.
matches = bf.match(des1, des2)
# Sort them in the order of their distance.
matches = sorted(matches, key=lambda x: x.distance)
# Draw first 10 matches.
img3 = cv2.drawMatches(image_a, kp1, image_b, kp2, matches[:100], None, flags=2)
return bgr_rgb(img3)
@time_cost
def sift_detect(img1, img2, detector='surf'):
if detector.startswith('si'):
print "sift detector......"
sift = cv2.xfeatures2d.SURF_create()
else:
print "surf detector......"
sift = cv2.xfeatures2d.SURF_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# BFMatcher with default params
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)
# Apply ratio test
good = [[m] for m, n in matches if m.distance < 0.5 * n.distance]
# cv2.drawMatchesKnn expects list of lists as matches.
img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good, None, flags=2)
return bgr_rgb(img3)
if __name__ == "__main__":
# load image
image_a = cv2.imread('./img1.jpg')
image_b = cv2.imread('./img2.png')
# ORB
# img = orb_detect(image_a, image_b)
# SIFT or SURF
img = sift_detect(image_a, image_b)
plt.imshow(img)
plt.show()
---------------------
作者:Eddy_zheng
来源:CSDN
原文:https://blog.csdn.net/Eddy_zheng/article/details/78916009
问题解决:
1.
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('cv version: ', cv2.__version__)?
在p3.6下所有print加括号
2.
import cPickle
ModuleNotFoundError: No module named 'cPickle'
python2有cPickle,但是在python3下,是没有cPickle的;
解决办法:将cPickle改为pickle
import pickle
File "F:/SIFT_SURF_1pic.py", line 51, in sift_detect
kp1, des1 = sift.detectAndCompute(img1, None)
error: OpenCV(3.4.2) C:\Miniconda3\conda-bld\opencv-suite_1534379934306\work\opencv_contrib-3.4.2\modules\xfeatures2d\src\surf.cpp:892: error: (-215:Assertion failed) !_img.empty() && ((imgtype) & ((1 << 3) - 1)) == 0 && (imgcn == 1 || imgcn == 3 || imgcn == 4) in function 'cv::xfeatures2d::SURF_Impl::detectAndCompute'
这个就是说你这行代码下的读取图片是空的
image_a = cv2.imread('./img1.jpg')
image_b = cv2.imread('./img2.png')
只要把图片放到你这个.py文件保存的路径下即可,子文件夹不可以
img1:
img2:
最后结果;