问题遇到的现象和发生背景
代码出自https://blog.csdn.net/cliukai/article/details/102467502
不知道哪里的路径需要改动
问题相关代码,请勿粘贴截图
import cv2
import numpy as np
import csv
import glob
class CoverDescriptor:
def describe(self,image):
#用BRISK方法对图片提取特征值
descriptor = cv2.BRISK_create()
#提取关键点和描述子,None对全图进行
(kps,descs) = descriptor.detectAndCompute(image, None)
kps = np.float32([kp.pt for kp in kps])
return (kps,descs)
class CoverMatcher:
def init(self,descriptor,coverPaths,ratio=0.7,minMatches=40,
useingHamming = True):
self.descriptor = descriptor
self.coverPaths = coverPaths
self.ratio = ratio
self.minMatcheers = minMatches
if useingHamming:
self.minMatcheers += "-Hamming"
def search(self,queryKps,queryDescs):
results = {}
for coverPath in self.coverPaths:
cover = cv2.imread(coverPath)
gray = cv2.cvtColor(cover,cv2.COLOR_BGR2GRAY)
(kps,descs) = self.descriptor.describle(gray)
score = self.match(queryKps,queryDescs,kps,descs)
results[coverPath] = score
if len(results) > 0:
results = sorted([(v,k) for (k,v) in results.items() if v > 0],
reverse = True)
return results
def match(self,kpsA,featuresA,kpsB,featuresB):
matchers = cv2.DescriptorMatcher_create(self.distanceMethod)
rawMatches = matcher.knnMatch(featuresB,featuresA,2)
matches = []
for m in rawMatches:
if len(m) == 2 and m[0].distance < m[1].distance * self.ratio:
matches.append((m[0].trainIdx,m[0].queryIdx))
if len(marches) > self.minMatches:
ptsA = np.float32([kpsA[i] for (i,_) in matches])
ptsB = np.float32([kpsB[j] for (_,j) in matches])
(_,status) = cv2.findHomography(ptsA,ptsB,cv2.RANSAC,4.0)
return float(status.sum()) / status.size
return -1.0
coverPath = r"C:\Users\蠡测\PycharmProjects\pythonProject1\test\source*.jpg"
queryPath = r"C:\Users\蠡测\PycharmProjects\pythonProject1\test\search\search1.jpg"
bookDatabasePath = "books.csv"
bokkDateebase = {}
for book in csv.reader(open(bookDatabasePath)):
bookDatabasePath[book[0]] = book[1:]
cd = CoverDescriptor()
cm = CoverDescriptor(cd,glob.glob(coverPath+"/*.jpg"),ratio=0.7,minMatches=40)
#加载查询图像
queryImage = cv2.imread(queryPath)
降噪,转换成灰度图
gray = cv2.cvtColor(queryImage, cv2.COLOR_BGR2GRAY)
提取关键点和描述子
(queryKps, queryDescs) = cd.describe(gray)
results = cm.search(queryKps,queryDescs)
#显示待查询的封面
cv2.imshow("query",queryImage)
#如果在数据库里没有找到书的封面
if len(results)==0:
print("该书暂未收录")
cv2.waitKey(0)
else:
for i,(score,coverPath) in enumerate(results):
(auther,title) = bookDatabase[coverPath[coverPath.rfind("\")+1:]]
print("loop{} precision is{:.2f}%: author is {} - title is {}".format(i+1,score*100,author,title))
result = cv2.imread(coverPath)
cv2.imshow("results",result)
cv2.waitKey(0)
cv2.destroyAllWindows()