方法综述
简单的图像分类可以采用HOG+SVM的算法,通过提取图像的HOG特征,然后特征通过SVM进行分类,实现图像的分类。
下面将代码的步骤讲清楚
提取HOG特征
#一种自定义的方法
def get_features(img):
#腐蚀后 锐化
#腐蚀
im_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#灰度图形
im=cv2.fastNlMeansDenoising(im_gray)
ret2,th2 = cv2.threshold(im,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)#自动找到阈值
img=np.array(th2)
plt.imshow(th2)
#print(features)
rows,cols=img.shape
#rows is h col is w
print(rows,cols)
#计算出各边的填充数量
top=(20-rows)//2
bottom=20-rows-top
left=(20-cols)//2
right=20-cols-left
constant = cv2.copyMakeBorder(img,top,bottom,left,right,cv2.BORDER_CONSTANT,value=[0])
#plt.imshow(constant)
hist=hog(constant)
feature=preprocessing.scale(hist)
return feature
def hog(img):
bin_n=16
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0)
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1)
mag, ang = cv2.cartToPolar(gx, gy)
bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16)
bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:]
mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10