训练文件
在项目中建立training文件夹,在其中存放你想要训练的图像,其中的小文件夹就是你训练生成的图像名称,可自行更改。
识别图像
建立testing文件夹,在其中存放你想要识别的图像。
LocalBinrayPatterns
from skimage import feature
import 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
import cv2
from LocalBinrayPatterns import LocalBinrayPatterns
from sklearn.svm import LinearSVC
from imutils import paths
import argparse
import 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()
运行结果展示
可以很明显的看出,提前存放的文件夹的图像训练成了相关文件夹名字的素材,而当检测到相关图片时,显示相关的名称。
后续
如果想了解更多物联网、智能家居项目知识,可以关注我的项目实战专栏。
或者关注公众号。
编写不易,感谢支持。