import cv2
import numpy as np
from os.path import join
datapath = "cardata/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匹配器有兩個引數:indexparams和searchparams,以字典的形式進行引數傳參
flann_params = dict(algorithm = 1, trees = 5)#1為flann_index_kdtree
matcher = cv2.flannbasedmatcher(flann_params, {})#匹配特徵
#建立bow訓練器,簇數為40
bow_kmeans_trainer = cv2.bowkmeanstrainer(40)
#初始化bow提取器
extract_bow = cv2.bowimgdescriptorextractor(extract, matcher)
def extract_sift(fn):#引數為路徑
im = cv2.imread(fn,0)
return extract.compute(im, detect.detect(im))[1]#返回描述符
#讀取8個正樣本和8個負樣本
for i in range(8):
bow_kmeans_trainer.add(extract_sift(path(pos,i)))
bow_kmeans_trainer.add(extract_sift(path(neg,i)))
#利用訓練器的cluster()函式,執行k-means分類並返回詞彙
#k-means:屬於聚類演算法,所謂的聚類演算法屬於無監督學習,將樣本x潛在所屬類別y找出來,具體稍後寫一篇補上
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))
#兩個陣列,分別為訓練資料和標籤,並用bow提取器產生的描述符填充
traindata, trainlabels = ,
for i in range(20):
#建立svm例項,將訓練資料和標籤放到numpy陣列中進行訓練,有關svm知識稍後寫一篇補上
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
#**結果
#新增文字說明
font = cv2.font_hershey_******x
if (car_predict[1][0][0] == 1.0):#predict結果為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):#predict結果為-1.0表示不能檢測到汽車
cv2.puttext(notcar_img,'car 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()
使用UIUC資料集進行汽車檢測
第二步驟 編寫 如下 import cv2 import numpy as np from os.path import join datapath home utryjc pictures trainimages def path cls,i return s s d.pgm datapath,c...
OpenCV人臉檢測
include include include include include include include include include include static cvmemstorage storage 0 建立乙個記憶體儲存器,來統一管理各種動態物件的記憶體 static cvhaar...
opencv 物件檢測
參考 1 官方文件api 2 d6 d00 tutorial py root.html 官方英文教程 3 4 高階教程 5 官方英文教程 6 7 8 opencv論壇 9 官方github 10 注 安裝的版本 opencv python 3.3.0 cp36 cp36m win amd64.whl...