import cv2
The import numpy as np
The from OS. Path import join
# placeholder path
Datapath="trainimages/"
Def path (CLS, I) :
Return % d.p gm/" % s % s "% (datapath, CLS, I + 1)
Pos and neg="pos", "neg"
Detect=cv2. Xfeatures2d. SIFT_create ()
Extract=cv2. Xfeatures2d. SIFT_create ()
Flann_params=dict (algorithm=1, trees=5)
The matcher=cv2. FlannBasedMatcher (flann_params, {})
Bow_kmeans_trainer=cv2. BOWKMeansTrainer (40)
Extract_bow=cv2. BOWImgDescriptorExtractor (extract, the matcher)
Def extract_sift (fn) :
Im=cv2. Imread (fn, 0)
Return extract.com pute (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.com pute (im, detect detect (im))
Traindata, trainlabels=[], []
For I in range (20) :
Traindata. The extend (bow_features (path (pos, I))); Trainlabels. Append (1)
Traindata. The extend (bow_features (path (neg, I))); Trainlabels. Append (1)
The 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])
The 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)
The font=cv2. FONT_HERSHEY_SIMPLEX
If (car_predict [1] [0] [0]==1.0) :
Cv2. PutText (car_img, 'Detected, (10, 30), the font, 1, (0255, 0), 2, cv2. LINE_AA)
If (not_car_predict [1] [0] [0]==1.0) :
Cv2. PutText (notcar_img, "Not Detected", (10, 30), the font, 1, (0, 0, 255), 2, cv2. LINE_AA)
Cv2. Imshow (' BOW + SVM Success, car_img)
Cv2. Imshow (' BOW + Failure SVM, notcar_img)
Cv2. WaitKey (0)
Cv2. DestroyAllWindows ()
When running error:
Traceback (the most recent call last) :
The File "G: \ python test demo \ test1012 \ text py", line 26, in & lt; 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 () function in CV: : BOWTrainer: : add
I can't find bagofwords on disk d., CPP file path does not exist, the back of the error also look not to understand, to obtain a great god help to look at, what specific error in the wrong place, thank you very much!!!!!
CodePudding user response:
Pos and neg="pos", "neg" a "-" symbolsCodePudding user response:
Bow_kmeans_trainer. Add (extract_sift (path (pos, I))) of the output to None, mainly function bow_kmeans_trainer how to do?CodePudding user response:
Can look at this article https://blog.csdn.net/qq_40456669/article/details/104198516