图像处理之角点检测算法(Harris Corner Detection)

简介: 图像处理之角点检测算法(Harris Corner Detection)

图像处理之角点检测算法(Harris Corner Detection)

Harris角点检测是通过数学计算在图像上发现角点特征的一种算法,而且其具有旋转不

性的特质。OpenCV中的Shi-Tomasi角点检测就是基于Harris角点检测改进算法。

基本原理:

角点是一幅图像上最明显与重要的特征,对于一阶导数而言,角点在各个方向的变化是

最大的,而边缘区域在只是某一方向有明显变化。一个直观的图示如下:


数学原理:

基本数学公式如下:

其中W(x, y)表示移动窗口,I(x, y)表示像素灰度值强度,范围为0~255。根据泰勒级数

计算一阶到N阶的偏导数,最终得到一个Harris矩阵公式:


根据Harris的矩阵计算矩阵特征值 ,然后计算Harris角点响应值:

其中K为系数值,通常取值范围为0.04 ~ 0.06之间。

算法详细步骤

第一步:计算图像X方向与Y方向的一阶高斯偏导数Ix与Iy

第二步:根据第一步结果得到Ix^2 , Iy^2与Ix*Iy值

第三步:高斯模糊第二步三个值得到Sxx, Syy, Sxy

第四部:定义每个像素的Harris矩阵,计算出矩阵的两个特质值

第五步:计算出每个像素的R值

第六步:使用3X3或者5X5的窗口,实现非最大值压制

第七步:根据角点检测结果计算,最提取到的关键点以绿色标记,显示在原图上。

程序关键代码解读

第一步计算一阶高斯偏导数的Ix与Iy值代码如下:

  filter.setDirectionType(GaussianDerivativeFilter.X_DIRECTION);
    BufferedImage xImage = filter.filter(grayImage, null);
    getRGB( xImage, 0, 0, width, height, inPixels );
    extractPixelData(inPixels, GaussianDerivativeFilter.X_DIRECTION, height, width);
    
    filter.setDirectionType(GaussianDerivativeFilter.Y_DIRECTION);
    BufferedImage yImage = filter.filter(grayImage, null);
    getRGB( yImage, 0, 0, width, height, inPixels );
    extractPixelData(inPixels, GaussianDerivativeFilter.Y_DIRECTION, height, width);

关于如何计算高斯一阶与二阶偏导数请看这里:

http://blog.csdn.net/jia20003/article/details/16369143

http://blog.csdn.net/jia20003/article/details/7664777

第三步:分别对第二步计算出来的三个值,单独进行高斯

模糊计算,代码如下:

  private void calculateGaussianBlur(int width, int height) {
        int index = 0;
        int radius = (int)window_radius;
        double[][] gw = get2DKernalData(radius, sigma);
        double sumxx = 0, sumyy = 0, sumxy = 0;
        for(int row=0; row<height; row++) {
          for(int col=0; col<width; col++) {            
            for(int subrow =-radius; subrow<=radius; subrow++)
            {
              for(int subcol=-radius; subcol<=radius; subcol++)
              {
                int nrow = row + subrow;
                int ncol = col + subcol;
                if(nrow >= height || nrow < 0)
                {
                  nrow = 0;
                }
                if(ncol >= width || ncol < 0)
                {
                  ncol = 0;
                }
                int index2 = nrow * width + ncol;
                HarrisMatrix whm = harrisMatrixList.get(index2);
                sumxx += (gw[subrow + radius][subcol + radius] * whm.getXGradient());
                sumyy += (gw[subrow + radius][subcol + radius] * whm.getYGradient());
                sumxy += (gw[subrow + radius][subcol + radius] * whm.getIxIy());
              }
            }
            index = row * width + col;
            HarrisMatrix hm = harrisMatrixList.get(index);
            hm.setXGradient(sumxx);
            hm.setYGradient(sumyy);
            hm.setIxIy(sumxy);
            
            // clean up for next loop
            sumxx = 0;
            sumyy = 0;
            sumxy = 0;
          }
        }   
  }

第六步:非最大信号压制(non-max value suppression)

这个在边源检测中是为了得到一个像素宽的边缘,在这里则

是为了得到准确的一个角点像素,去掉非角点值。代码如下:

  /***
   * we still use the 3*3 windows to complete the non-max response value suppression
   */
  private void nonMaxValueSuppression(int width, int height) {
        int index = 0;
        int radius = (int)window_radius;
        for(int row=0; row<height; row++) {
          for(int col=0; col<width; col++) {
            index = row * width + col;
            HarrisMatrix hm = harrisMatrixList.get(index);
            double maxR = hm.getR();
            boolean isMaxR = true;
            for(int subrow =-radius; subrow<=radius; subrow++)
            {
              for(int subcol=-radius; subcol<=radius; subcol++)
              {
                int nrow = row + subrow;
                int ncol = col + subcol;
                if(nrow >= height || nrow < 0)
                {
                  nrow = 0;
                }
                if(ncol >= width || ncol < 0)
                {
                  ncol = 0;
                }
                int index2 = nrow * width + ncol;
                HarrisMatrix hmr = harrisMatrixList.get(index2);
                if(hmr.getR() > maxR)
                {
                  isMaxR = false;
                }
              }             
            }
            if(isMaxR)
            {
              hm.setMax(maxR);
            }
          }
        }
    
  }

运行效果:


程序完整源代码:

package com.gloomyfish.image.harris.corner;
 
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
 
import com.gloomyfish.filter.study.GrayFilter;
 
public class HarrisCornerDetector extends GrayFilter {
  private GaussianDerivativeFilter filter;
  private List<HarrisMatrix> harrisMatrixList;
  private double lambda = 0.04; // scope : 0.04 ~ 0.06
  
  // i hard code the window size just keep it' size is same as 
  // first order derivation Gaussian window size
  private double sigma = 1; // always
  private double window_radius = 1; // always
  public HarrisCornerDetector() {
    filter = new GaussianDerivativeFilter();
    harrisMatrixList = new ArrayList<HarrisMatrix>();
  }
 
  @Override
  public BufferedImage filter(BufferedImage src, BufferedImage dest) {
    int width = src.getWidth();
        int height = src.getHeight();
        initSettings(height, width);
        if ( dest == null )
            dest = createCompatibleDestImage( src, null );
        
        BufferedImage grayImage = super.filter(src, null);
        int[] inPixels = new int[width*height];
        
    // first step  - Gaussian first-order Derivatives (3 × 3) - X - gradient, (3 × 3) - Y - gradient
    filter.setDirectionType(GaussianDerivativeFilter.X_DIRECTION);
    BufferedImage xImage = filter.filter(grayImage, null);
    getRGB( xImage, 0, 0, width, height, inPixels );
    extractPixelData(inPixels, GaussianDerivativeFilter.X_DIRECTION, height, width);
    
    filter.setDirectionType(GaussianDerivativeFilter.Y_DIRECTION);
    BufferedImage yImage = filter.filter(grayImage, null);
    getRGB( yImage, 0, 0, width, height, inPixels );
    extractPixelData(inPixels, GaussianDerivativeFilter.Y_DIRECTION, height, width);
        
    // second step - calculate the Ix^2, Iy^2 and Ix^Iy
    for(HarrisMatrix hm : harrisMatrixList)
    {
      double Ix = hm.getXGradient();
      double Iy = hm.getYGradient();
      hm.setIxIy(Ix * Iy);
      hm.setXGradient(Ix*Ix);
      hm.setYGradient(Iy*Iy);
    }
    
    // 基于高斯方法,中心点化窗口计算一阶导数和,关键一步 SumIx2, SumIy2 and SumIxIy, 高斯模糊
    calculateGaussianBlur(width, height);
 
    // 求取Harris Matrix 特征值 
    // 计算角度相应值R R= Det(H) - lambda * (Trace(H))^2
    harrisResponse(width, height);
    
    // based on R, compute non-max suppression
    nonMaxValueSuppression(width, height);
    
    // match result to original image and highlight the key points
    int[] outPixels = matchToImage(width, height, src);
    
    // return result image
    setRGB( dest, 0, 0, width, height, outPixels );
    return dest;
  }
  
  
  private int[] matchToImage(int width, int height, BufferedImage src) {
    int[] inPixels = new int[width*height];
        int[] outPixels = new int[width*height];
        getRGB( src, 0, 0, width, height, inPixels );
        int index = 0;
        for(int row=0; row<height; row++) {
          int ta = 0, tr = 0, tg = 0, tb = 0;
          for(int col=0; col<width; col++) {
            index = row * width + col;
            ta = (inPixels[index] >> 24) & 0xff;
                tr = (inPixels[index] >> 16) & 0xff;
                tg = (inPixels[index] >> 8) & 0xff;
                tb = inPixels[index] & 0xff;
                HarrisMatrix hm = harrisMatrixList.get(index);
                if(hm.getMax() > 0)
                {
                  tr = 0;
                  tg = 255; // make it as green for corner key pointers
                  tb = 0;
                  outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb;
                }
                else
                {
                  outPixels[index] = (ta << 24) | (tr << 16) | (tg << 8) | tb;                  
                }
                
          }
        }
    return outPixels;
  }
  /***
   * we still use the 3*3 windows to complete the non-max response value suppression
   */
  private void nonMaxValueSuppression(int width, int height) {
        int index = 0;
        int radius = (int)window_radius;
        for(int row=0; row<height; row++) {
          for(int col=0; col<width; col++) {
            index = row * width + col;
            HarrisMatrix hm = harrisMatrixList.get(index);
            double maxR = hm.getR();
            boolean isMaxR = true;
            for(int subrow =-radius; subrow<=radius; subrow++)
            {
              for(int subcol=-radius; subcol<=radius; subcol++)
              {
                int nrow = row + subrow;
                int ncol = col + subcol;
                if(nrow >= height || nrow < 0)
                {
                  nrow = 0;
                }
                if(ncol >= width || ncol < 0)
                {
                  ncol = 0;
                }
                int index2 = nrow * width + ncol;
                HarrisMatrix hmr = harrisMatrixList.get(index2);
                if(hmr.getR() > maxR)
                {
                  isMaxR = false;
                }
              }             
            }
            if(isMaxR)
            {
              hm.setMax(maxR);
            }
          }
        }
    
  }
  
  /***
   * 计算两个特征值,然后得到R,公式如下,可以自己推导,关于怎么计算矩阵特征值,请看这里:
   * http://www.sosmath.com/matrix/eigen1/eigen1.html
   * 
   *  A = Sxx;
   *  B = Syy;
   *  C = Sxy*Sxy*4;
   *  lambda = 0.04;
   *  H = (A*B - C) - lambda*(A+B)^2;
     *
   * @param width
   * @param height
   */
  private void harrisResponse(int width, int height) {
        int index = 0;
        for(int row=0; row<height; row++) {
          for(int col=0; col<width; col++) {
            index = row * width + col;
            HarrisMatrix hm = harrisMatrixList.get(index);
            double c =  hm.getIxIy() * hm.getIxIy();
            double ab = hm.getXGradient() * hm.getYGradient();
            double aplusb = hm.getXGradient() + hm.getYGradient();
            double response = (ab -c) - lambda * Math.pow(aplusb, 2);
            hm.setR(response);
          }
        }   
  }
 
  private void calculateGaussianBlur(int width, int height) {
        int index = 0;
        int radius = (int)window_radius;
        double[][] gw = get2DKernalData(radius, sigma);
        double sumxx = 0, sumyy = 0, sumxy = 0;
        for(int row=0; row<height; row++) {
          for(int col=0; col<width; col++) {            
            for(int subrow =-radius; subrow<=radius; subrow++)
            {
              for(int subcol=-radius; subcol<=radius; subcol++)
              {
                int nrow = row + subrow;
                int ncol = col + subcol;
                if(nrow >= height || nrow < 0)
                {
                  nrow = 0;
                }
                if(ncol >= width || ncol < 0)
                {
                  ncol = 0;
                }
                int index2 = nrow * width + ncol;
                HarrisMatrix whm = harrisMatrixList.get(index2);
                sumxx += (gw[subrow + radius][subcol + radius] * whm.getXGradient());
                sumyy += (gw[subrow + radius][subcol + radius] * whm.getYGradient());
                sumxy += (gw[subrow + radius][subcol + radius] * whm.getIxIy());
              }
            }
            index = row * width + col;
            HarrisMatrix hm = harrisMatrixList.get(index);
            hm.setXGradient(sumxx);
            hm.setYGradient(sumyy);
            hm.setIxIy(sumxy);
            
            // clean up for next loop
            sumxx = 0;
            sumyy = 0;
            sumxy = 0;
          }
        }   
  }
  
  public double[][] get2DKernalData(int n, double sigma) {
    int size = 2*n +1;
    double sigma22 = 2*sigma*sigma;
    double sigma22PI = Math.PI * sigma22;
    double[][] kernalData = new double[size][size];
    int row = 0;
    for(int i=-n; i<=n; i++) {
      int column = 0;
      for(int j=-n; j<=n; j++) {
        double xDistance = i*i;
        double yDistance = j*j;
        kernalData[row][column] = Math.exp(-(xDistance + yDistance)/sigma22)/sigma22PI;
        column++;
      }
      row++;
    }
    
//    for(int i=0; i<size; i++) {
//      for(int j=0; j<size; j++) {
//        System.out.print("\t" + kernalData[i][j]);
//      }
//      System.out.println();
//      System.out.println("\t ---------------------------");
//    }
    return kernalData;
  }
 
  private void extractPixelData(int[] pixels, int type, int height, int width)
  {
        int index = 0;
        for(int row=0; row<height; row++) {
          int ta = 0, tr = 0, tg = 0, tb = 0;
          for(int col=0; col<width; col++) {
            index = row * width + col;
            ta = (pixels[index] >> 24) & 0xff;
                tr = (pixels[index] >> 16) & 0xff;
                tg = (pixels[index] >> 8) & 0xff;
                tb = pixels[index] & 0xff;
                HarrisMatrix matrix = harrisMatrixList.get(index);
                if(type == GaussianDerivativeFilter.X_DIRECTION)
                {
                  matrix.setXGradient(tr);
                }
                if(type == GaussianDerivativeFilter.Y_DIRECTION)
                {
                  matrix.setYGradient(tr);
                }
          }
        }
  }
  
  private void initSettings(int height, int width)
  {
        int index = 0;
        for(int row=0; row<height; row++) {
          for(int col=0; col<width; col++) {
            index = row * width + col;
            HarrisMatrix matrix = new HarrisMatrix();
                harrisMatrixList.add(index, matrix);
          }
        }
  }
 
}

最后注意:

我是把彩色图像变为灰度图像来计算,这个计算量小点

处理容易点,此外很多图像处理软件都会用标记来显示

关键点像素,我没有,只是将关键点像素改为绿色。

所以可以从这些方面有很大的提高空间。

相关文章
|
1月前
|
监控 安全 算法
137_安全强化:输入过滤与水印 - 实现输出水印的检测算法与LLM安全防护最佳实践
随着大语言模型(LLM)在各行业的广泛应用,安全问题日益凸显。从提示注入攻击到恶意输出生成,从知识产权保护到内容溯源,LLM安全已成为部署和应用过程中不可忽视的关键环节。在2025年的LLM技术生态中,输入过滤和输出水印已成为两大核心安全技术,它们共同构建了LLM服务的安全防护体系。
|
24天前
|
机器学习/深度学习 算法 机器人
使用哈里斯角Harris和SIFT算法来实现局部特征匹配(Matlab代码实现)
使用哈里斯角Harris和SIFT算法来实现局部特征匹配(Matlab代码实现)
119 8
|
2月前
|
传感器 资源调度 算法
DDMA-MIMO雷达多子带相干累积目标检测算法——论文阅读
本文提出一种多子带相干累积(MSCA)算法,通过引入空带和子带相干处理,解决DDMA-MIMO雷达的多普勒模糊与能量分散问题。该方法在低信噪比下显著提升检测性能,实测验证可有效恢复目标速度,适用于车载雷达高精度感知。
377 4
DDMA-MIMO雷达多子带相干累积目标检测算法——论文阅读
|
1月前
|
开发框架 算法 .NET
基于ADMM无穷范数检测算法的MIMO通信系统信号检测MATLAB仿真,对比ML,MMSE,ZF以及LAMA
简介:本文介绍基于ADMM的MIMO信号检测算法,结合无穷范数优化与交替方向乘子法,降低计算复杂度并提升检测性能。涵盖MATLAB 2024b实现效果图、核心代码及详细注释,并对比ML、MMSE、ZF、OCD_MMSE与LAMA等算法。重点分析LAMA基于消息传递的低复杂度优势,适用于大规模MIMO系统,为通信系统检测提供理论支持与实践方案。(238字)
|
2月前
|
canal 算法 vr&ar
【图像处理】基于电磁学优化算法的多阈值分割算法研究(Matlab代码实现)
【图像处理】基于电磁学优化算法的多阈值分割算法研究(Matlab代码实现)
105 1
|
5月前
|
机器学习/深度学习 运维 监控
实时异常检测实战:Flink+PAI 算法模型服务化架构设计
本文深入探讨了基于 Apache Flink 与阿里云 PAI 构建的实时异常检测系统。内容涵盖技术演进、架构设计、核心模块实现及金融、工业等多领域实战案例,解析流处理、模型服务化、状态管理等关键技术,并提供性能优化与高可用方案,助力企业打造高效智能的实时异常检测平台。
414 1
|
4月前
|
存储 监控 算法
基于跳表数据结构的企业局域网监控异常连接实时检测 C++ 算法研究
跳表(Skip List)是一种基于概率的数据结构,适用于企业局域网监控中海量连接记录的高效处理。其通过多层索引机制实现快速查找、插入和删除操作,时间复杂度为 $O(\log n)$,优于链表和平衡树。跳表在异常连接识别、黑名单管理和历史记录溯源等场景中表现出色,具备实现简单、支持范围查询等优势,是企业网络监控中动态数据管理的理想选择。
132 0
|
24天前
|
机器学习/深度学习 算法 机器人
【水下图像增强融合算法】基于融合的水下图像与视频增强研究(Matlab代码实现)
【水下图像增强融合算法】基于融合的水下图像与视频增强研究(Matlab代码实现)
142 0
|
1月前
|
数据采集 分布式计算 并行计算
mRMR算法实现特征选择-MATLAB
mRMR算法实现特征选择-MATLAB
118 2
|
2月前
|
传感器 机器学习/深度学习 编解码
MATLAB|主动噪声和振动控制算法——对较大的次级路径变化具有鲁棒性
MATLAB|主动噪声和振动控制算法——对较大的次级路径变化具有鲁棒性
177 3

热门文章

最新文章