opencv 官网,有关特征检测识别的库函数及介绍:
- https://docs.opencv.org/4.3.0/db/d27/tutorial_py_table_of_contents_feature2d.html
ORB特征匹配库函数介绍、使用:
- https://docs.opencv.org/4.3.0/d1/d89/tutorial_py_orb.html
import numpy as np import cv2 as cv from matplotlib import pyplot as plt img = cv.imread('simple.jpg',0) # Initiate ORB detector orb = cv.ORB_create() # find the keypoints with ORB kp = orb.detect(img,None) # compute the descriptors with ORB kp, des = orb.compute(img, kp) # draw only keypoints location,not size and orientation img2 = cv.drawKeypoints(img, kp, None, color=(0,255,0), flags=0) plt.imshow(img2), plt.show()
示例结果图片:
想要做一个输入目标图片,在测试图片上寻找目标,最后得到中心点坐标。但检测测试中,效果不好,所以只做了简单实验没往下做定位。不知道是不是因为我这个案例不适合做orb,网上做orb+Homography定位目标的也有,如下几个:
- https://verytoolz.com/blog/ee68cfe884/
- https://blog.csdn.net/qq_45832961/article/details/122769532
- https://www.jianshu.com/p/d835f1a4717c?tdsourcetag=s_pctim_aiomsg
- https://blog.csdn.net/zhoujinwang/article/details/128279154
实践测试中,使用如下为输入图片,左图为测试图片,右图为目标图片:
测试图片 目标图片
测试代码:
import cv2 as cv def ORB_Feature(img1, img2): # 初始化ORB orb = cv.ORB_create() # 寻找关键点 kp1 = orb.detect(img1) kp2 = orb.detect(img2) # 计算描述符 kp1, des1 = orb.compute(img1, kp1) kp2, des2 = orb.compute(img2, kp2) # 画出关键点 outimg1 = cv.drawKeypoints(img1, keypoints=kp1, outImage=None) outimg2 = cv.drawKeypoints(img2, keypoints=kp2, outImage=None) # 显示关键点 # import numpy as np # outimg3 = np.hstack([outimg1, outimg2]) # cv.imshow("Key Points", outimg3) # cv.waitKey(0) # 初始化 BFMatcher bf = cv.BFMatcher(cv.NORM_HAMMING) # 对描述子进行匹配 matches = bf.match(des1, des2) # 计算最大距离和最小距离 min_distance = matches[0].distance max_distance = matches[0].distance for x in matches: if x.distance < min_distance: min_distance = x.distance if x.distance > max_distance: max_distance = x.distance # 筛选匹配点 ''' 当描述子之间的距离大于两倍的最小距离时,认为匹配有误。 但有时候最小距离会非常小,所以设置一个经验值30作为下限。 ''' good_match = [] for x in matches: if x.distance <= max(2 * min_distance, 30): good_match.append(x) # 绘制匹配结果 draw_match(img1, img2, kp1, kp2, good_match) def draw_match(img1, img2, kp1, kp2, match): outimage = cv.drawMatches(img1, kp1, img2, kp2, match[:25], outImg=None) cv.imshow("Match Result", outimage) cv.waitKey(0) def rescale_image(img,opt,times): if opt == "up": scale_up_x = int(times) scale_up_y = int(times) return cv.resize(img, None, fx= scale_up_x, fy= scale_up_y, interpolation= cv.INTER_LINEAR) if opt == "down": scale_down = int(times) return cv.resize(img, None, fx= scale_down, fy= scale_down, interpolation= cv.INTER_LINEAR) if __name__ == '__main__': # 读取图片 image1 = cv.imread('orb1.png') image2 = cv.imread('orb2.png') image2 = rescale_image(image2, opt="up", times=5) ORB_Feature(image1, image2)
测试结果:(不怎么理想)