写一段图像预处理然后计算图像的梯度然后划分图像为小的单元格然后组合单元格内的梯度直方图然后对于每个块内的直方图进行归一化,最后将所有块内的归一化直方图连接起来,形成一个HOG特征的代码
时间: 2024-06-10 08:10:58 浏览: 30
# 图像预处理
import cv2
img = cv2.imread('image.jpg', 0)
img = cv2.resize(img, (128, 128)) # 调整图像大小
img = cv2.GaussianBlur(img, (3, 3), 0) # 高斯滤波
# 计算梯度
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=1)
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=1)
mag, ang = cv2.cartToPolar(gx, gy, angleInDegrees=True)
# 划分图像为小的单元格
cell_size = 8
cell_step = cell_size // 2
height, width = img.shape
num_cells_x = width // cell_size
num_cells_y = height // cell_size
# 组合单元格内的梯度直方图
bins = 9
histograms = np.zeros((num_cells_y, num_cells_x, bins))
for i in range(num_cells_y):
for j in range(num_cells_x):
cell_mag = mag[i * cell_size:(i + 1) * cell_size,
j * cell_size:(j + 1) * cell_size]
cell_ang = ang[i * cell_size:(i + 1) * cell_size,
j * cell_size:(j + 1) * cell_size]
histograms[i, j, :] = np.histogram(cell_ang,
bins=bins,
range=(0., 180.),
weights=cell_mag)[0]
# 归一化每个块内的直方图
eps = 1e-7
block_size = 2
num_blocks_x = (num_cells_x - block_size) + 1
num_blocks_y = (num_cells_y - block_size) + 1
normalized_blocks = np.zeros((num_blocks_y, num_blocks_x,
block_size * block_size * bins))
for i in range(num_blocks_y):
for j in range(num_blocks_x):
block = histograms[i:i + block_size, j:j + block_size, :]
normalized = block / np.sqrt(np.sum(block ** 2) + eps ** 2)
normalized_blocks[i, j, :] = normalized.ravel()
# 连接所有块内的归一化直方图,形成HOG特征
hog_feature = normalized_blocks.ravel()
阅读全文