Opencv Q&A_11
2022/03/23
基于knn通过特征值识别和比较分类
代码_Feature_Detect.py(main)
import cv2 as cv import utlis dirpath = 'D:\work\\automation\Skill\Python\pythonWORK\cv\material\Feature_sample' cap = cv.VideoCapture(1) imgs = utlis.getImg(dirpath) feats1 = utlis.findFeature(imgs[0]) while True: flag,frame = cap.read() try: if frame is not None: feat2 = utlis.findFeature([frame]) utlis.featureMatch(frame,feats1,feat2[0],imgs[1]) cv.imshow('img',frame) cv.waitKey(1) except: print('something has happened')
代码_utlis.py
import cv2 as cv import os def getImg(path): ### 自动读取全部图片,返回图片数组和名字列表 imgs = [] namelist = [] classlist = os.listdir(path) for item in classlist: name = item.rstrip('.jpg') namelist.append(name) img = cv.imread(path + '\\' + item) imgs.append(img) return [imgs,namelist] def findFeature(imgs): ### 找到并返回特征值 deslist = [] orb = cv.ORB_create(3000) for img in imgs: kp,des = orb.detectAndCompute(img,None) deslist.append(des) return deslist def featureMatch(img,des1,des2,namelist): ### 匹配特征值进行分类 max = 0 count = 0 bf = cv.BFMatcher() for num,des in enumerate(des1): good = [] matchs = bf.knnMatch(des,des2,k=2) for m,n in matchs: if m.distance < 0.75 * n.distance: good.append(m) len_good = len(good) if len_good > 15: if len_good > max: max = len_good count = num cv.putText(img,namelist[count],(80,80),cv.FONT_HERSHEY_SIMPLEX,3,(0,255,0),3)
运行效果
遇到的问题
Q1:容易发生错误的点
A1:utlis.py中,findFeature()函数参数为图片数组集合,当输入只有一张图片时,应该加上[]