Haar-like特征

haar特征多用于人脸检测、行人检测等;Haar-like特征可以理解为卷积模板;该模板的特征值为白色矩形像素和减去黑色矩形像素和,反映了图像的灰度变化情况,但矩形特征只对一些简单的图形结构,如边缘、线段较敏感,所以只能描述特定走向(水平、垂直、对角)的结构。

Haar-like特征分类

Haar-like特征可以分为四类:线性特征、边缘特征、点特征(中心特征)、对角线特征:

积分图

计算haar特征值

 def intergral(self,image):
        height,weigth = np.shape(image)
        output = np.zeros((height + 1,weigth + 1))
         
        for h in range(1,height + 1):
            columnSum = np.zeros((weigth + 1))  
            for w in range(1,weigth + 1):
                columnSum[w] = columnSum[w - 1] + image[h - 1][w - 1] # 每行的列合计
                output[h][w] = output[h - 1][w] + columnSum[w]
        return output

   def HaarRectPyramidUp(self,imageSize,minSize=1,minDeep=2):
        size = minSize
        deep = minDeep

        yield size,deep
     
        while True:
            if size < deep:
                size = size + 1
                deep = size * minDeep
            else:
                deep = deep + 1
                size = deep * minSize
             
            if max(size,deep) > imageSize:
                break
            if size == deep and size * 2 > imageSize:
                break
                 
            yield size,deep

    def Haar2RectLR(self, sum, minSize=1, minDeep=2):
        '''
        b |       d|       e|
        --------------------
          | white  | black  |
        --------------------
        c | white a| black f|

        # white= a+ b-c-d
        '''
        height,weigth = np.shape(sum)  

        feature_map = []
        for size,deep in self.HaarRectPyramidUp(weigth - 1,minSize,minDeep):     
            for y in range(1,height - deep + 1):
                for x in range(1,weigth - 2 * size + 1):  
                    by = dy = ey = y - 1
                    cy = ay = fy = y + deep - 1

                    bx = cx = x - 1
                    dx = ax = x + size - 1
                    ex = fx = x + size * 2 - 1
                     
                    white = sum[ay][ax] + sum[by][bx] - sum[cy][cx] - sum[dy][dx]
                    black = sum[fy][fx] + sum[dy][dx] - sum[ay][ax] - sum[ey][ex]
      
                    feature_map.append(int(white) - int(black))  
        return feature_map

    def GetHaarFeatureDescriptor(self,images,imgSize):
        features = []
        for fn in images:  
            # 读入彩色图像,并转换为灰度值图像
            img = cv2.imread(fn, cv2.IMREAD_GRAYSCALE)
              
            # 图片拉伸
            img = cv2.resize(img, imgSize, interpolation=cv2.INTER_CUBIC)
             
            # 归一化
            img = img / float(np.max(img)) * 255

            # 积分图
            intim = self.intergral(img)    

            # 垂直方向边缘特征
            feature = self.Haar2RectLR(intim) 
 
            features.append(feature)
             
        return features

猜你喜欢

转载自blog.csdn.net/lk3030/article/details/84038029