HOG特征提取算法python
时间: 2025-03-04 21:52:29 浏览: 42
HOG 特征提取算法 Python 实现与应用
使用 scikit-image 库实现 HOG 特征提取
为了简化开发过程并提高效率,可以利用 scikit-image
这一强大的图像处理库来进行 HOG 特征的提取。下面是一个简单的例子展示如何使用该库完成这项工作:
from skimage import feature, color, io
import matplotlib.pyplot as plt
# 加载图片并转换成灰度图
image = color.rgb2gray(io.imread('path_to_image'))
# 计算HOG特征向量以及可视化后的HOG图像
fd, hog_image = feature.hog(image, orientations=9, pixels_per_cell=(8, 8),
cells_per_block=(2, 2), visualize=True)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
ax1.axis('off')
ax1.imshow(image, cmap=plt.cm.gray)
ax1.set_title('Input Image')
# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 10))
ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax2.set_title('HOG Visualization')
plt.show()
这段代码展示了加载一张彩色图片后将其转为灰度模式,并调用 feature.hog()
函数获取其对应的 HOG 描述符和可视化的 HOG 图像[^1]。
自定义实现 HOG 特征提取
对于更深入的理解或特殊需求下的调整,也可以尝试自己编写 HOG 提取函数。这里给出一个基于 NumPy 和 SciPy 的简单版本:
import numpy as np
import cv2
import math
def compute_gradient_magnitude_and_angle(gray_img):
grad_x = cv2.Sobel(gray_img, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)
grad_y = cv2.Sobel(gray_img, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1)
mag, angle = cv2.cartToPolar(grad_x, grad_y, angleInDegrees=True)
return mag, angle
class HogDescriptor:
def __init__(self, img, cell_size=16, bin_size=9):
self.img = img
self.cell_size = cell_size
self.bin_size = bin_size
h, w = img.shape[:2]
cx, cy = int(cell_size / 2), int(cell_size / 2)
# Compute gradient magnitude and direction
mag, ang = compute_gradient_magnitude_and_angle(img)
# Normalize angles to range [0, pi]
ang %= 180
hist_tensor = []
for y in range(cy, h-cy, cell_size):
row_hist = []
for x in range(cx, w-cx, cell_size):
# Extract a single cell from the image
cell_mag = mag[y:y+cell_size, x:x+cell_size]
cell_ang = ang[y:y+cell_size, x:x+cell_size]
# Create histograms per cell based on orientation bins
hist = np.zeros(bin_size, dtype=float)
for i in range(cell_size):
for j in range(cell_size):
bin_idx = int((cell_ang[i,j]/180)*bin_size)%bin_size
hist[bin_idx] += cell_mag[i,j]
row_hist.append(hist)
hist_tensor.append(row_hist)
self.histograms = np.asarray(hist_tensor)
if __name__ == "__main__":
gray_img = cv2.cvtColor(cv2.imread("your_image_path"), cv2.COLOR_BGR2GRAY)
descriptor = HogDescriptor(gray_img)
print(descriptor.histograms.shape)
上述代码实现了方向梯度直方图(HOG)描述子的手动构建流程,包括计算每个像素点处的方向角和幅值、创建细胞单元格内的直方图等操作[^3]。
方向梯度直方图概念简介
方向梯度直方图(Histogram of Oriented Gradients, HOG)作为一种有效的视觉形状描述方法,在计算机视觉领域有着广泛应用。它通过对输入图像的不同局部区域内计算边缘强度变化情况来捕捉目标对象的空间分布特性。具体来说就是先求得各位置上的梯度大小及角度信息,再按照一定规则划分成多个小区间形成直方图表示形式;最后将这些直方图连接起来作为整个区域的对象表征[^4]。
相关推荐



















