參考資料:
Histogram of Oriented Gradients
斯坦福CS131-1718作業(yè)3艇劫、作業(yè)7
目標64×128×3-->3780
-
預(yù)處理
剪出一個patch衣摩,縮放為64×128
-
計算梯度圖像
-
在8×8的單元格內(nèi)計算HOG
8×8×3 經(jīng)過梯度計算得到8×8×2(2是分別是梯度大小和方向)最后再表示成9個柱子的直方圖,可以用大小為9的數(shù)組來表示缘滥,越來越緊湊。單獨的梯度可能是噪聲谒主,但8×8計算出來魯棒性比較好完域。
8×8是個超參數(shù),這對于64×128的行人圖像比較合適地可以獲取我們感興趣的特征瘩将,人臉吟税,頭等等凹耙。
所有梯度根據(jù)方向分成9個格子,每個格子累加它們的幅度肠仪。
下圖的計算過程:165度余20等于5,5/20=1/4,因此高的bin得到1/4肖抱,低的bin得到3/4。165在160~180中有3/4异旧,在0度只有1/4意述。每個格子代表的是一個刻度,不是一個區(qū)間吮蛹。165介于160和180(0)度之間荤崇,其中比較偏向于160度,故160度有3/4,180(0)度只有1/4潮针。
可以看到下面的圖片在0和180度附近的梯度幅度累加比較大术荤,說明在這個方向上變化比較大。
-
16×16 Block Normalization
為了不讓光照影響上面的梯度計算每篷,采用L2 規(guī)范化瓣戚,向量除以向量長度。
一個16×16的patch可以根據(jù)前面步驟計算出4×9的特征向量焦读,然后進行規(guī)范化子库;16×16的各自繼續(xù)向右移動8個像素,重復上述操作矗晃。換行的時候也是移動8個像素仑嗅。所以一張64×128的圖像有8×16個8×8的格子,16×16的窗口按照上面的方式可以計算7×15次张症,每次有36個元素仓技,故一共為7×15×36=3780元素
其主要的思想還是投票算法的思想,梯度之類的都是老套路了吠冤。
-
算法具體實現(xiàn)
作業(yè)3用HOG在用harris選出角點后浑彰,需要配對兩幅圖片中對應(yīng)的點,需要一個descriptor來描述一個個點附近的patch拯辙,后面好比較郭变。簡單的就是直接normalize,然后flatten涯保,也就是NCC诉濒,這里改用hog。hog是根據(jù)patch梯度來的夕春。
def hog_descriptor(patch, pixels_per_cell=(8,8)):
"""
patch一般是16*16未荒,cell是小的單元格,只有8*8
Generating hog descriptor by the following steps:
1. compute the gradient image in x and y (already done for you)
2. compute gradient histograms
3. normalize across block
4. flattening block into a feature vector
Args:
patch: grayscale image patch of shape (h, w)
pixels_per_cell: size of a cell with shape (m, n)
Returns:
block: 1D array of shape ((h*w*n_bins)/(m*n))
"""
assert (patch.shape[0] % pixels_per_cell[0] == 0),\
'Heights of patch and cell do not match'
assert (patch.shape[1] % pixels_per_cell[1] == 0),\
'Widths of patch and cell do not match'
n_bins = 9
degrees_per_bin = 180 // n_bins
Gx = filters.sobel_v(patch)
Gy = filters.sobel_h(patch)
# Unsigned gradients
G = np.sqrt(Gx**2 + Gy**2)
theta = (np.arctan2(Gy, Gx) * 180 / np.pi) % 180
G_cells = view_as_blocks(G, block_shape=pixels_per_cell)
theta_cells = view_as_blocks(theta, block_shape=pixels_per_cell)
rows = G_cells.shape[0]
cols = G_cells.shape[1]
cells = np.zeros((rows, cols, n_bins))
# Compute histogram per cell
### YOUR CODE HERE
cell_rows,cell_cols = pixels_per_cell
# 2. compute gradient histograms
# r,c是patch中cell的定位及志,c_r,c_c是cell中每個元素的定位
for r in range(rows):
for c in range(cols):
for c_r in range(cell_rows):
for c_c in range(cell_cols):
degree = theta_cells[r][c][c_r][c_c]
value = G_cells[r][c][c_r][c_c]
lower_bin = int(degree / degrees_per_bin) % n_bins
upper_bin = (lower_bin + 1) % n_bins
ratio = float(degree % degrees_per_bin) / degrees_per_bin
cells[r][c][lower_bin] += (1 - ratio) * value
cells[r][c][upper_bin] += ratio * value
block = (cells/np.linalg.norm(cells)).flatten()
### YOUR CODE HERE
return block
-
HOG用于檢測是否是人臉
作業(yè)7
計算多張已對齊的人臉的平均臉片排,和對應(yīng)的HOG特征
檢測是否是人臉
用窗口滑過檢測的圖片寨腔,選出一個個窗口,計算HOG率寡,每次都跟上面計算出來的HOG特征向量進行點擊迫卢,值比較大的地方就是人臉。
缺點
如果對圖片進行縮放冶共,那么可能就會識別錯誤乾蛤,這個就需要用金字塔來表示圖片了,見金字塔博客捅僵。