import cv2
import numpy as np
from os.path import join
# placeholder path
datapath = "trainimages/"
def path(cls,i):
return "%s/%s%d.pgm" % (datapath,cls,i+1)
pos, neg = "pos", "neg"
detect = cv2.xfeatures2d.SIFT_create()
extract = cv2.xfeatures2d.SIFT_create()
flann_params = dict(algorithm = 1, trees = 5)
matcher = cv2.FlannBasedMatcher(flann_params, {})
bow_kmeans_trainer = cv2.BOWKMeansTrainer(40)
extract_bow = cv2.BOWImgDescriptorExtractor(extract, matcher)
def extract_sift(fn):
im = cv2.imread(fn,0)
return extract.compute(im, detect.detect(im))[1]
for i in range(8):
bow_kmeans_trainer.add(extract_sift(path(pos,i)))
bow_kmeans_trainer.add(extract_sift(path(neg,i)))
voc = bow_kmeans_trainer.cluster()
extract_bow.setVocabulary( voc )
def bow_features(fn):
im = cv2.imread(fn,0)
return extract_bow.compute(im, detect.detect(im))
traindata, trainlabels = [],[]
for i in range(20):
traindata.extend(bow_features(path(pos, i))); trainlabels.append(1)
traindata.extend(bow_features(path(neg, i))); trainlabels.append(-1)
svm = cv2.ml.SVM_create()
svm.train(np.array(traindata), cv2.ml.ROW_SAMPLE, np.array(trainlabels))
def predict(fn):
f = bow_features(fn);
p = svm.predict(f)
print (fn, "\t", p[1][0][0])
return p
# again placeholder paths
car, notcar = "xxmd3,jpg", "no.jpg"
car_img = cv2.imread(car)
notcar_img = cv2.imread(notcar)
car_predict = predict(car)
not_car_predict = predict(notcar)
font = cv2.FONT_HERSHEY_SIMPLEX
if (car_predict[1][0][0] == 1.0):
cv2.putText(car_img,'Detected',(10,30), font, 1,(0,255,0),2,cv2.LINE_AA)
if (not_car_predict[1][0][0] == -1.0):
cv2.putText(notcar_img,' Not Detected',(10,30), font, 1,(0,0, 255),2,cv2.LINE_AA)
cv2.imshow('BOW + SVM Success', car_img)
cv2.imshow('BOW + SVM Failure', notcar_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行的时候 出现错误:
Traceback (most recent call last):
File "G:\python test demo\test1012\text.py", line 26, in <module>
bow_kmeans_trainer.add(extract_sift(path(pos,i)))
cv2.error: D:\Build\OpenCV\opencv-3.3.0\modules\features2d\src\bagofwords.cpp:55: error: (-215) !_descriptors.empty() in function cv::BOWTrainer::add
但是根据描述我在d盘找不到bagofwords.cpp文件,路径不存在。后面的错误也看不明白,恳请大神帮忙看看,具体错误错在什么地方,万分感谢!!
5 个解决方案
#1
#2
你好,我最近也在弄这个程序,请问你的问题解决了嘛??
#3
#4
我也遇到了这个问题,报错跟你差不多,经大神指点,我这里是图片本身的问题。你可以慢慢查一查第25行,range()里的数,看看从哪个数开始报错,我的是从neg-129开始的,所以我把neg-130对应的图片用neg-(last)替换掉了(注:分辨率要与原图一致),然后就跑通了
#5
您好,我现在也是遇到这个问题,也是-129。您的意思是把图片名字改成last吗?还是其他的方法。然后可以稍微解释一下吗。
#1
#2
你好,我最近也在弄这个程序,请问你的问题解决了嘛??
#3
#4
我也遇到了这个问题,报错跟你差不多,经大神指点,我这里是图片本身的问题。你可以慢慢查一查第25行,range()里的数,看看从哪个数开始报错,我的是从neg-129开始的,所以我把neg-130对应的图片用neg-(last)替换掉了(注:分辨率要与原图一致),然后就跑通了
#5
您好,我现在也是遇到这个问题,也是-129。您的意思是把图片名字改成last吗?还是其他的方法。然后可以稍微解释一下吗。