HOG特征提取分四步
一、将在x,y方向上的差分图谱笛卡尔坐标转换成极坐标获取HOG特征,HOG特征分两副特征图谱,分别是长度图谱、角度图谱
二、分别对长度图谱与角度图谱进行切割,重组,切割的最小单元为重组后的细胞元,也就是将原二维图谱变为四维图谱
三、将每个细胞元进行提取特征,也就是提取特征向量(角度、长度),值得注意的是提取特征向量时需考虑权重,也就是对应角度在左右两边所占的比例
四、每个细胞元的特征向量与周围2*2的范围内特征向量进行归一化,连接所有细胞元特征向量,作为整幅图的特征向量
代码如下:
import numpy as np
import cv2
path = 'test.jpg'
image = cv2.imread(path,0)
image = cv2.resize(image,(64,128))
#进行差分,提取边缘
gx = cv2.Sobel(image,cv2.CV_32F,dx=1,dy=0)
gy = cv2.Sobel(image,cv2.CV_32F,dx=0,dy=1)
#将笛卡尔坐标转换成极坐标
mag,ang = cv2.cartToPolar(gx,gy,angleInDegrees=True)
#设置细胞元大小及整幅图中各维度细胞元数量
cells_x = 16
cells_y = 8
cells_w = 8
#对图像进行切割重组,增加维度,二维变四维
def devil_ag(mag,cells_x,cells_y,cells_w):
new_map = np.zeros((cells_x,cells_y,cells_w,cells_w))
mag_x = np.split(mag,cells_x,axis=0)
for i,l in enumerate(mag_x):
mag_x[i] = np.asarray(l)
mag_y = np.split(mag_x[i],cells_y,axis=1)
for j,l1 in enumerate(mag_y):
mag_y[j] = np.asarray(l1)
new_map[i,j] = mag_y[j]
return new_map
#对角度谱图与长度谱图提取特征,获取细胞元特征向量
def get_bins(mag_cell,ang_cell):
bin_num = 9
bins = [0.0]*bin_num
offset = 20
mag_list = mag_cell.flatten()
ang_list = ang_cell.flatten()
for i,ang in enumerate(ang_list):
if ang>=180:
ang -= 180
left = int(ang/offset)
right = left+1 if left!=bin_num-1 else 0
left_ration = ang/offset - left
right_ration = 1-left_ration
bins[left] = mag_list[i]*left_ration
bins[right] = mag_list[i]*right_ration
return bins
hist = []
mag_cells = devil_ag(mag,16,8,8)
ang_cells = devil_ag(ang,16,8,8)
#对特征向量进行2*2范围内的归一化
for i in range(cells_x-1):
for j in range(cells_y-1):
mag_sum = np.sum(mag_cells[i][j])+np.sum(mag_cells[i+1][j])+np.sum(mag_cells[i][j+1])+np.sum(mag_cells[i+1][j+1])
hist.extend(get_bins(mag_cells[i][j]/mag_sum,ang_cells[i][j]))
hist.extend(get_bins(mag_cells[i+1][j]/mag_sum,ang_cells[i+1][j]))
hist.extend(get_bins(mag_cells[i][j+1]/mag_sum,ang_cells[i][j+1]))
hist.extend(get_bins(mag_cells[i+1][j+1]/mag_sum,ang_cells[i+1][j+1]))
print(hist)