这周三robomasters的大佬要纳新了,还说让带着博客去,赶紧来更新一期(为了大佬看着方便,我给每一行都加上了注释,大佬且慢端详),考虑了上次的KNN属于慵懒机器学习算法且准确率还那么低,这次换成SVM试一试。
我没有选用sk-learn的手写体数据集的原因是他的数据集每张图片是8×8的,而我下载的mnist的digits是一张包含5000张手写体图片的1000×2000的图片,也就是每张手写体图片是20×20的,心想也许这样的准确率会比较好。
这是这次的效果图,准确率也不是很好。
这是该程序的准确率和初始化时间。
用MNIST自己的数据测试的准确率很高,可是测自己的手写体准确率很低,好多人都有这个问题,可能是写字的笔不一样吧。。。
看程序。
S.1 划分数据集
def initSvm():
img = cv2.imread('digits.png') #读取数据集
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转灰度图
cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)] #划分数据集
train = np.array(cells).reshape(-1,400).astype(np.float32) #将图片转为行向量
trainLabel = np.repeat(np.arange(10),500) #建立索引
return train, trainLabel
S.2 寻找数字位置,并预测数值
def findRoi(frame, thresValue):
rois = []
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray2 = cv2.dilate(gray,None,iterations=2) #两次膨胀
gray2 = cv2.erode(gray2,None,iterations=2) #两次腐蚀
edges = cv2.absdiff(gray,gray2) #做差,建立sobel算子进行边缘检测
x = cv2.Sobel(edges,cv2.CV_16S,1,0)
y = cv2.Sobel(edges,cv2.CV_16S,0,1)
absX = cv2.convertScaleAbs(x)
absY = cv2.convertScaleAbs(y)
dst = cv2.addWeighted(absX,0.5,absY,0.5,0)
ret, ddst = cv2.threshold(dst,thresValue,255,cv2.THRESH_BINARY) #转为二值图
im, contours, hierarchy = cv2.findContours(ddst,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #寻找边界
for c in contours:
x, y, w, h = cv2.boundingRect(c)
if w > 10 and h > 20:
rois.append((x,y,w,h))
digits = []
for r in rois:
x, y, w, h = r
digit= findDigit(edges[y:y+h,x:x+w], 50) #预测数值
#digits.append(cv2.resize(th,(20,20)))
cv2.rectangle(frame, (x,y), (x+w,y+h), (153,153,0), 2) #绘制矩形框
cv2.putText(frame, str(digit), (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1, (127,0,255), 2) #绘制预测数字
return edges
def findDigit(roi, thresValue):
ret, th = cv2.threshold(roi, thresValue, 255, cv2.THRESH_BINARY)
th = cv2.resize(th,(20,20)) #图片转为20×20
out = th.reshape(-1,400).astype(np.float32) #图片转为行向量
result = lsvc.predict(out) #预测结果
return result
S.3 训练模型,输出初始化时间及准确率
X, Y = initSvm()
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
ss = StandardScaler() #数据标准化
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
lsvc = LinearSVC()
lsvc.fit(X_train, y_train) #训练模型
y_predict = lsvc.predict(X_test) #预测测试数据集
print 'The Accuracy of Linear SVC is: ', lsvc.score(X_test, y_test) #获得评分
endtime = datetime.datetime.now()
print 'The time of SVM init is: ', (endtime - starttime).seconds, 's' #计算初始化时间
S.4 打开摄像头,开始吧!
cap = cv2.VideoCapture(0)
width = 426*2
height = 480
videoFrame = cv2.VideoWriter('frame.avi',cv2.VideoWriter_fourcc('M','J','P','G'),25,(int(width),int(height)),True)
while True:
ret, frame = cap.read()
frame = frame[:,:426]
edges = findRoi(frame, 50)
newEdges = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
newFrame = np.hstack((frame,newEdges))
cv2.imshow('frame', newFrame)
videoFrame.write(newFrame) #保存视频
key = cv2.waitKey(1) & 0xff
if key == ord('q'):
break
完整代码如下
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
from sklearn.cross_validation import train_test_split
import datetime
starttime = datetime.datetime.now()
def initSvm():
img = cv2.imread('digits.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]
train = np.array(cells).reshape(-1,400).astype(np.float32)
trainLabel = np.repeat(np.arange(10),500)
return train, trainLabel
def findRoi(frame, thresValue):
rois = []
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray2 = cv2.dilate(gray,None,iterations=2)
gray2 = cv2.erode(gray2,None,iterations=2)
edges = cv2.absdiff(gray,gray2)
x = cv2.Sobel(edges,cv2.CV_16S,1,0)
y = cv2.Sobel(edges,cv2.CV_16S,0,1)
absX = cv2.convertScaleAbs(x)
absY = cv2.convertScaleAbs(y)
dst = cv2.addWeighted(absX,0.5,absY,0.5,0)
ret, ddst = cv2.threshold(dst,thresValue,255,cv2.THRESH_BINARY)
im, contours, hierarchy = cv2.findContours(ddst,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
x, y, w, h = cv2.boundingRect(c)
if w > 10 and h > 20:
rois.append((x,y,w,h))
digits = []
for r in rois:
x, y, w, h = r
digit= findDigit(edges[y:y+h,x:x+w], 50)
#digits.append(cv2.resize(th,(20,20)))
cv2.rectangle(frame, (x,y), (x+w,y+h), (153,153,0), 2)
cv2.putText(frame, str(digit), (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1, (127,0,255), 2)
return edges
def findDigit(roi, thresValue):
ret, th = cv2.threshold(roi, thresValue, 255, cv2.THRESH_BINARY)
th = cv2.resize(th,(20,20))
out = th.reshape(-1,400).astype(np.float32)
result = lsvc.predict(out)
return result
X, Y = initSvm()
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
lsvc = LinearSVC()
lsvc.fit(X_train, y_train)
y_predict = lsvc.predict(X_test)
print 'The Accuracy of Linear SVC is: ', lsvc.score(X_test, y_test)
endtime = datetime.datetime.now()
print 'The time of SVM init is: ', (endtime - starttime).seconds, 's'
cap = cv2.VideoCapture(0)
width = 426*2
height = 480
videoFrame = cv2.VideoWriter('frame.avi',cv2.VideoWriter_fourcc('M','J','P','G'),25,(int(width),int(height)),True)
while True:
ret, frame = cap.read()
frame = frame[:,:426]
edges = findRoi(frame, 50)
newEdges = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
newFrame = np.hstack((frame,newEdges))
cv2.imshow('frame', newFrame)
videoFrame.write(newFrame)
key = cv2.waitKey(1) & 0xff
if key == ord('q'):
break
参考原文:http://blog.csdn.net/uestc_c2_403/article/details/72848831