如何基于SLIC超像素与HOG图像获取各超像素的HOG描述符?
获取超像素的HOG描述符解决方案
嘿,我来帮你搞定这个问题!你已经完成了HOG特征提取和SLIC超像素分割,现在只需要把两者结合起来,就能为每个超像素计算对应的HOG描述符。下面是具体的实现思路和代码:
核心思路
先明确几个关键对应关系:
segments_slic是224×224的数组,每个元素代表对应原图像像素所属的超像素标签;hog_image对应的cell级HOG特征是14×14×8的结构(因为你设置了pixels_per_cell=(16,16),224÷16=14,每个cell包含8个方向的HOG值);- 我们需要把原图像中每个超像素包含的所有像素,映射到对应的HOG cell,再对每个超像素内的所有cell的HOG特征进行聚合(这里用平均作为示例,你也可以根据需求换成求和、最大值等方式)。
实现代码
import numpy as np from skimage.feature import hog from skimage.segmentation import slic from skimage.color import rgb2gray # 模拟输入(假设image是加载好的224×224×3 RGB图像) image = np.random.rand(224, 224, 3) # 计算HOG特征(获取结构化的cell级特征) gray_image = rgb2gray(image) # 设置feature_vector=False,得到未扁平化的cell级HOG特征 hog_features = hog( gray_image, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), feature_vector=False ) # 重塑为(14,14,8)的简洁结构 hog_features = hog_features.reshape(14, 14, 8) # 执行SLIC超像素分割(设置n_segments=100匹配预期输出) segments_slic = slic(image, n_segments=100, compactness=0.01, sigma=1) num_superpixels = len(np.unique(segments_slic)) # 定义生成超像素HOG描述符的函数 def hog_superpixels(segments, hog_cells): img_h, img_w = segments.shape cell_h, cell_w, num_orient = hog_cells.shape # 计算每个HOG cell对应的原图像像素块尺寸 cell_size = img_h // cell_h # 这里是16 # 初始化超像素描述符数组 superpixel_descs = np.zeros((num_superpixels, num_orient)) # 遍历每个超像素标签 for sp_label in np.unique(segments): # 获取当前超像素的所有像素坐标 y_coords, x_coords = np.where(segments == sp_label) # 将像素坐标转换为对应的HOG cell坐标 cell_y = y_coords // cell_size cell_x = x_coords // cell_size # 提取这些cell对应的HOG特征 sp_hog_vals = hog_cells[cell_y, cell_x, :] # 用平均聚合得到超像素的HOG描述符 superpixel_descs[sp_label] = np.mean(sp_hog_vals, axis=0) return superpixel_descs # 调用函数得到结果 superpixels_descriptors = hog_superpixels(segments_slic, hog_features) print(superpixels_descriptors.shape) # 输出:(100, 8),符合预期
关键细节说明
- HOG特征结构化处理:通过
feature_vector=False获取未扁平化的cell级HOG特征,重塑后更方便按cell索引操作; - 坐标映射逻辑:原图像像素坐标整除cell尺寸(16),就能得到对应的HOG cell位置;
- 特征聚合方式:示例用了平均值,你可以根据任务需求替换成求和、最大值等,调整
np.mean为对应的函数即可。
内容的提问来源于stack exchange,提问作者eric lardon
相关产品推荐
相关产品推荐

