本代码参考的图书是《Opencv 3计算机视觉 Python语言实现(原书第二版)》。python版本3.6;opencv版本3.3.0。代码如下:
import cv2
import numpy as np
from os.path import join
# placeholder path
datapath = "C:/Users/ZXY/Desktop/mubiaogenzong/TrainImages"
def path(cls,i):
return "%s/%s%d.pgm" % (datapath,cls,i)
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)#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)))
#print(path(pos,i))
bow_kmeans_trainer.add(extract_sift(path(neg,i)))
#print(path(neg,i))
#print(bow_kmeans_trainer)
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(8):
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 = "C:/Users/ZXY/Desktop/mubiaogenzong/car.jpg", "C:/Users/ZXY/Desktop/mubiaogenzong/bb.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,'Car 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,'Car Not Detected',(10,30), font, 1,(0,255,0),2,cv2.LINE_AA)
cv2.imshow('BOW + SVM Success', car_img)
cv2.imshow('BOW + SVM Failure', notcar_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
其中用到的图片正负样本(.jpg)在文件夹名为<图片>下,转换成的灰度图片(.pgm)在文文件夹名为
走过的坑:
1、error: (-215) !_descriptors.empty() in function cv::BOWTrainer::add
原因:不详。
解决办法:灰度图片所在文件夹不要有其他无关图片。
2、训练结果不准确,我遇到的是龙妈训练到的结果显示是符合正样本,即不显示“Car Not Detected”字样。
原因:负样本也许差距太大,之前我用的负样本都是人物头像。
解决办法:我把负样本换成道路的图片,结果还可以。
用到的图片资料:https://pan.baidu.com/s/1aDrNSxMowcwzWQp6R9Kh0Q
提取码:c2la