写一个HOG提取图片特征的例子
时间: 2024-06-12 22:04:16 浏览: 8
以下是一个HOG提取图片特征的例子:
```python
import cv2
import numpy as np
# 读取图片
img = cv2.imread('example.jpg')
# 转为灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 计算梯度
gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=1)
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=1)
# 计算梯度幅值和方向
mag, ang = cv2.cartToPolar(gx, gy, angleInDegrees=True)
# 划分cell
cell_size = (8, 8)
cell_h, cell_w = cell_size
h, w = gray.shape[:2]
num_cells_h, num_cells_w = (h // cell_h, w // cell_w)
# 划分block
block_size = (2, 2)
block_h, block_w = block_size
num_blocks_h, num_blocks_w = (num_cells_h - block_h + 1, num_cells_w - block_w + 1)
# 计算每个cell的直方图
histogram = np.zeros((num_cells_h, num_cells_w, 9), dtype=np.float32)
cell_gradient = np.zeros((cell_h, cell_w, 9), dtype=np.float32)
angle_unit = 360 / 9
for i in range(9):
angle_start = i * angle_unit
angle_end = (i + 1) * angle_unit
indices = np.where(np.logical_and(ang >= angle_start, ang < angle_end))
cell_gradient[..., i][indices] = mag[..., i][indices]
for y in range(num_cells_h):
for x in range(num_cells_w):
cell_histogram = histogram[y, x]
cell_histogram[:] = cell_gradient[y * cell_h:(y + 1) * cell_h, x * cell_w:(x + 1) * cell_w, :].sum(axis=(0, 1))
# 正则化
eps = 1e-7
for y in range(num_blocks_h):
for x in range(num_blocks_w):
block_histogram = histogram[y:y + block_h, x:x + block_w, :].flatten()
block_norm = np.sqrt(np.sum(block_histogram ** 2) + eps ** 2)
histogram[y:y + block_h, x:x + block_w, :] = block_histogram / block_norm
# 展开为特征向量
features = histogram.flatten()
```
在上面的例子中,我们首先读取了一张图片,然后将其转换为灰度图。接着,我们计算了图片的梯度信息,并根据梯度信息计算每个像素点的梯度幅值和方向。然后,我们将图片划分为若干个cell,并在每个cell上计算一个9维的直方图,用来表示该cell内不同方向的梯度信息。接着,我们将相邻的若干个cell组成一个block,并对每个block内的cell的直方图进行归一化,最终将所有block的直方图展开为一个特征向量。这个特征向量就是图片的HOG特征。