[Python与图像处理]Python提取图像HOG特征

采用Python、numpy库实现图像HOG特征的提取,主要用于分析HOG特征的具体算法流程。
参考链接:https://blog.csdn.net/qq_37141382/article/details/89342081
参考资料:
HOG的经典论文:Dalal N, Triggs B. Histograms of oriented gradients for human detection[C]//Computer Vision and Pattern Recognition, 2005. CVPR 2005. IEEE Computer Society Conference on. IEEE, 2005, 1: 886-893.(2016:Google Citation: 14046)

HOG特征提取算法的整个实现过程大致如下:
1、读入所需要的图像;
2、将RGB图像转为灰度图像(将输入的彩色的图像的r,g,b值通过特定公式转换为灰度值);
3、采用Gamma校正法对输入图像进行颜色空间的标准化(归一化);
4、计算图像每个像素的梯度(包括大小和方向),捕获轮廓信息;
5、统计每个cell(以88为例)的梯度直方图(不同梯度方向的幅值),形成每个cell的feature descriptor;
6、将4个cell组成一个block(以2
2为例),一个block内4个cell的特征串联起来得到该block的HOG特征descriptor;
7、将图像内所有block的HOG特征descriptor串联起来得到该图像的HOG特征descriptor,这就是最终分类的特征向量。

Python代码,根据自己的需要改变cell的大小,block的大小:

#coding:utf-8
#*********************************************************************************************************
'''
说明:利用python/numpy/opencv实现图像HOG特征的提取
算法思路:
算法思路:
        1)以灰度图的方式加载图片,resize到(128,64);
        2)灰度图像gamma校正;
		3)利用一阶微分算子Sobel函数,分别计算出灰度图像X方向和Y方向上的一阶微分/梯度图像,根据得到的两幅
        梯度图像(X方向上的梯度图像和Y方向上的梯度图像),计算出这两幅梯度图像所对应的梯度幅值图像gradient_magnitude、
        梯度方向图像gradient_angle
		4)构造(cell_x = 128/8 =16, cell_y= 64/8 =8)大小的cell图像----梯度幅值的grad_cell图像,梯度方向的ang_cell图像,
        每个cell包含有8*8 = 64个值;
		5)将每个cell根据角度值(0-180)分为9个bin,并计算每个cell中的梯度方向直方图,每个cell有9个值;
		6)每(2*2)个cell为一个block,总共15*7个block,计算每个block的梯度方向直方图,并进行归一化处理,每个block中有9*4=36个值;
		7)计算整幅图像的梯度方向直方图HOG:将计算出来的所有的Block的HOG梯度方向直方图的特征向量首尾相接组成一个维度很大的向量
        长度为:15*7*36 = 3780,
        这个特征向量就是整幅图像的梯度方向直方图特征,这个特征可用于SVM分类。
'''
import cv2
import numpy as np
import matplotlib.pyplot as plt

#灰度图像gamma校正
def gamma(img):
    #不同参数下的gamma校正
    # img1 = img.copy()
    # img2 = img.copy()
    # img1 = np.power( img1 / 255.0, 0.5 )
    # img2 = np.power( img2 / 255.0, 2.2 )
    return np.power( img / 255.0, 1 )    

#获取梯度值cell图像,梯度方向cell图像
def div( img, cell_x, cell_y, cell_w ):
    cell = np.zeros( shape = ( cell_x, cell_y, cell_w, cell_w ) )
    img_x = np.split( img, cell_x, axis = 0 )
    for i in range( cell_x ):
        img_y = np.split( img_x[i], cell_y, axis = 1 )
        for j in range( cell_y ):
            cell[i][j] = img_y [j]
    return cell

#获取梯度方向直方图图像,每个像素点有9个值
def get_bins( grad_cell, ang_cell ):
    bins = np.zeros( shape = ( grad_cell.shape[0], grad_cell.shape[1], 9 ) )
    for i in range( grad_cell.shape[0] ):
        for j in range( grad_cell.shape[1] ):
            binn = np.zeros(9)
            grad_list = np.int8( grad_cell[i,j].flatten() )#每个cell中的64个梯度值展平,并转为整数
            ang_list = ang_cell[i,j].flatten()#每个cell中的64个梯度方向展平)
            ang_list = np.int8( ang_list / 20.0 )#0-9
            ang_list[ ang_list >=9 ] = 0
            for m in range(len(ang_list)):
                binn[ang_list[m]] += int( grad_list[m] )#不同角度对应的梯度值相加,为直方图的幅值
          #每个cell的梯度方向直方图可视化
            # N = 9
            # x = np.arange( N )
            # str1 = ( '0-20', '20-40', '40-60', '60-80', '80-100', '100-120', '120-140', '140-160', '160-180' )
            # plt.bar( x, height = binn, width = 0.8, label = 'cell histogram', tick_label = str1 )
            # for a, b in zip(x, binn):
                # plt.text( a, b+0.05, '{}'.format(b), ha = 'center', va = 'bottom', fontsize = 10 )
            # plt.show()
            bins[i][j] = binn
    return bins

#计算图像HOG特征向量,长度为 15*7*36 = 3780   
def hog( img, cell_x, cell_y, cell_w ):
    height, width = img.shape
    gradient_values_x = cv2.Sobel( img, cv2.CV_64F, 1, 0, ksize = 5 )#x方向梯度
    gradient_values_y = cv2.Sobel( img, cv2.CV_64F, 0, 1, ksize = 5 )#y方向梯度
    gradient_magnitude = np.sqrt( np.power( gradient_values_x, 2 ) + np.power( gradient_values_y, 2 ) )
    gradient_angle = np.arctan2( gradient_values_x, gradient_values_y )
    print( gradient_magnitude.shape, gradient_angle.shape )
    # plt.figure()
    # plt.subplot( 1, 2, 1 )
    # plt.imshow(gradient_angle)
    #角度转换至(0-180)
    gradient_angle[ gradient_angle > 0 ] *= 180 / 3.14
    gradient_angle[ gradient_angle < 0 ] = ( gradient_angle[ gradient_angle < 0 ] + 3.14 ) *180 / 3.14
    # plt.subplot( 1, 2, 2 )
    # plt.imshow( gradient_angle )
    # plt.show()

    grad_cell = div( gradient_magnitude, cell_x, cell_y, cell_w )
    ang_cell = div( gradient_angle, cell_x, cell_y, cell_w )
    bins = get_bins ( grad_cell, ang_cell )
    feature = []
    for i in range( cell_x - 1 ):
        for j in range( cell_y - 1 ):
            tmp = []
            tmp.append( bins[i,j] )
            tmp.append( bins[i+1,j] )
            tmp.append( bins[i,j+1] )
            tmp.append( bins[i+1,j+1] )
            tmp -= np.mean( tmp )
            feature.append( tmp.flatten() )
    return np.array( feature ).flatten()
                
if __name__ == '__main__':
    img = cv2.imread( './data/basketball1.png', cv2.IMREAD_GRAYSCALE )
    if( img is None ):
        print( 'Not read image.' )
    print( img.shape )
    resizeimg = cv2.resize( img, ( 128, 64 ), interpolation = cv2.INTER_CUBIC )
    cell_w = 8
    cell_x = int( resizeimg.shape[0] / cell_w )#cell行数
    cell_y = int( resizeimg.shape[1] / cell_w )#cell列数
    print( 'The size of cellmap is {}*{} '.format( cell_x, cell_y ) )
    gammaimg = gamma( resizeimg )*255    
    feature = hog( gammaimg, cell_x, cell_y, cell_w )
    print( feature.shape )
  • 26
    点赞
  • 196
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: HOG(Histogram of Oriented Gradients)是一种计算机视觉中的特征提取算法,常用于目标检测和行人识别等任务中。在Python中,可以使用OpenCV或scikit-image等库来实现HOG特征提取。 以scikit-image为例,可以通过以下代码实现HOG特征提取: ``` from skimage.feature import hog from skimage import data, exposure # 读取图像 image = data.astronaut() # 计算HOG特征 fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualize=True, multichannel=True) # 对HOG特征进行可视化 hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 10)) # 显示原始图像HOG特征图像 import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True) ax1.axis('off') ax1.imshow(image, cmap=plt.cm.gray) ax1.set_title('Input image') 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('Histogram of Oriented Gradients') plt.show() ``` 其中,`image`代表输入的图像,`orientations`指定方向的个数,`pixels_per_cell`指定每个细胞的像素数,`cells_per_block`指定每个块包含的细胞数。`fd`表示提取得到的HOG特征向量,`hog_image`表示HOG特征图像。最后,使用`matplotlib`库进行可视化,显示原始图像HOG特征图像。 ### 回答2: HOG(Histogram of Oriented Gradients)特征提取是一种用于计算图像特征的方法,最初是由Navneet Dalal和Bill Triggs在2005年提出的。它在计算机视觉领域被广泛应用于物体检测和图像分类任务。 HOG特征提取的过程可以分为以下几个步骤: 1. 归一化图像大小:为了保持计算效率,首先需要将图像缩放为固定的大小。通常,使用缩放后的图像尺寸在64x128到128x256之间。 2. 计算梯度:对于每个像素,通过计算其在水平和垂直方向上的梯度,确定其梯度的大小和方向。这些梯度用于描述图像的边缘和纹理信息。 3. 划分图像为小单元:将缩放后的图像划分为一系列重叠的小单元。每个小单元通常为8x8像素。 4. 创建梯度方向直方图:对于每个小单元,根据其中像素的梯度方向和大小,创建梯度方向直方图。一个直方图通常包含9个方向的梯度值。 5. 归一化块:将相邻的若干小单元组合成块,并对每个块内的直方图进行归一化处理。这有助于提高特征的鲁棒性和可区分性。 6. 拼接特征向量:将所有块的特征向量拼接在一起,形成最终的HOG特征向量。 HOG特征提取通过描述图像中梯度的方向信息来提取特征,而不是关注像素的具体值。这使得HOG特征对于光照变化和几何变换相对不敏感,具有较好的鲁棒性。在图像处理和计算机视觉任务中,HOG特征已被广泛应用于人体检测、行人检测、物体识别等领域。 ### 回答3: HOG(方向梯度直方图)是一种计算机视觉领域常用的特征提取算法,它用于对图像进行描述和识别。Python中有各种库和模块可以用来实现HOG特征提取HOG特征提取的步骤如下: 1. 图像预处理:将图像转化为灰度图,如果图像尺寸较大,还可以进行降采样。 2. 计算图像的梯度:使用Sobel等算子计算图像在水平和竖直方向上的梯度。计算梯度的目的是为了检测图像中的边缘和纹理。 3. 划分图像为小的块(cells):将图像分割为大小固定的小块,每个小块包含多个像素。 4. 计算每个小块的梯度直方图:对于每个小块,统计其内像素的梯度方向和强度,并将其组织成直方图。 5. 归一化梯度直方图:对于每个小块的梯度直方图,可以对其进行归一化,使得特征对光照等变化更加不敏感。 6. 将小块的特征组合成一个全局的特征向量:将所有小块的特征向量进行串联,形成一个用于描述整个图像的全局特征向量。 通过以上步骤,我们可以得到一个用于描述图像HOG特征向量。这个特征向量可以用于识别和分类任务,比如行人检测、物体识别等。 在Python中,我们可以使用第三方库如OpenCV或scikit-image来实现HOG特征提取。这些库提供了方便的函数和方法,可以直接使用。 例如,使用OpenCV库,我们可以使用以下代码来实现HOG特征提取: ```python import cv2 def hog_feature_extraction(image): # 图像预处理 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 创建HOG对象 hog = cv2.HOGDescriptor() # 计算HOG特征向量 features = hog.compute(gray) return features ``` 上述代码中,我们首先将彩色图像转换为灰度图像,然后创建一个HOG对象,并使用`compute`函数计算图像HOG特征向量。 总结来说,Python中可以使用第三方库实现HOG特征提取,该特征提取方法可以用于图像描述和识别任务,具有良好的性能和鲁棒性。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值