使用LBP+SVM,训练识别给定的测试图像

2021-02-02 13:59:30 浏览数 (3)

训练文件

在项目中建立training文件夹,在其中存放你想要训练的图像,其中的小文件夹就是你训练生成的图像名称,可自行更改。

识别图像

建立testing文件夹,在其中存放你想要识别的图像。

LocalBinrayPatterns

代码语言:javascript复制
from skimage import featureimport numpy as np
class LocalBinrayPatterns:    def __init__(self,numPoints,radius):        self.numPoints = numPoints        self.radius = radius
    def describle(self,image,esp=1e-7):        lbp = feature.local_binary_pattern(image,self.numPoints,self.radius,method="uniform")        (hist,_) = np.histogram(lbp.ravel(),bins=np.arange(0,self.numPoints   3),range=(0,self.numPoints   2))
        hist = hist.astype("float")        hist /= (hist.sum()   esp)        return hist

recognize

代码语言:javascript复制
import cv2from LocalBinrayPatterns import LocalBinrayPatternsfrom sklearn.svm import LinearSVCfrom imutils import pathsimport argparseimport os

ap = argparse.ArgumentParser()ap.add_argument("-t","--training",default="./training",help="path to the training images")ap.add_argument("-e","--testing",default="./testing",help="path to the testing images")args = vars(ap.parse_args())

desc = LocalBinrayPatterns(24,8)data = []labels = []

for imagePath in paths.list_images(args["training"]):    image = cv2.imread(imagePath)    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)    hist = desc.describle(gray)
    labels.append(imagePath.split(os.path.sep)[-2])    data.append(hist)
model = LinearSVC(C=100.0,random_state=42)model.fit(data, labels)


for imagePath in paths.list_images(args["testing"]):
    image = cv2.imread(imagePath)    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)    hist = desc.describle(gray)    prediction = model.predict(hist.reshape(1,-1))

    cv2.putText(image, prediction[0],(10,30),cv2.FONT_HERSHEY_SIMPLEX,1.0,(0,0,255),3)    cv2.imshow("Image",image)    cv2.waitKey(0)
cv2.destroyWindow()

运行结果展示

可以很明显的看出,提前存放的文件夹的图像训练成了相关文件夹名字的素材,而当检测到相关图片时,显示相关的名称。

1 人点赞