android中霍夫变换检测圆

来源:互联网 发布:人工智能 蒋里博士 编辑:程序博客网 时间:2024/04/23 19:18

图像处理之霍夫变换圆检测算法

之前写过一篇文章讲述霍夫变换原理与利用霍夫变换检测直线, 结果发现访问量还是蛮

多,有点超出我的意料,很多人都留言说代码写得不好,没有注释,结构也不是很清晰,所以

我萌发了再写一篇,介绍霍夫变换圆检测算法,同时也尽量的加上详细的注释,介绍代码

结构.让更多的人能够读懂与理解.

一:霍夫变换检测圆的数学原理


根据极坐标,圆上任意一点的坐标可以表示为如上形式, 所以对于任意一个圆, 假设

中心像素点p(x0, y0)像素点已知, 圆半径已知,则旋转360由极坐标方程可以得到每

个点上得坐标同样,如果只是知道图像上像素点, 圆半径,旋转360°则中心点处的坐

标值必定最强.这正是霍夫变换检测圆的数学原理.

二:算法流程

该算法大致可以分为以下几个步骤


三:运行效果

图像从空间坐标变换到极坐标效果, 最亮一点为圆心.


图像从极坐标变换回到空间坐标,检测结果显示:


四:关键代码解析

个人觉得这次注释已经是非常的详细啦,而且我写的还是中文注释

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * 霍夫变换处理 - 检测半径大小符合的圆的个数 
  3.  * 1. 将图像像素从2D空间坐标转换到极坐标空间 
  4.  * 2. 在极坐标空间中归一化各个点强度,使之在0〜255之间 
  5.  * 3. 根据极坐标的R值与输入参数(圆的半径)相等,寻找2D空间的像素点 
  6.  * 4. 对找出的空间像素点赋予结果颜色(红色) 
  7.  * 5. 返回结果2D空间像素集合 
  8.  * @return int [] 
  9.  */  
  10. public int[] process() {  
  11.   
  12.     // 对于圆的极坐标变换来说,我们需要360度的空间梯度叠加值  
  13.     acc = new int[width * height];  
  14.     for (int y = 0; y < height; y++) {  
  15.         for (int x = 0; x < width; x++) {  
  16.             acc[y * width + x] = 0;  
  17.         }  
  18.     }  
  19.     int x0, y0;  
  20.     double t;  
  21.     for (int x = 0; x < width; x++) {  
  22.         for (int y = 0; y < height; y++) {  
  23.   
  24.             if ((input[y * width + x] & 0xff) == 255) {  
  25.   
  26.                 for (int theta = 0; theta < 360; theta++) {  
  27.                     t = (theta * 3.14159265) / 180// 角度值0 ~ 2*PI  
  28.                     x0 = (int) Math.round(x - r * Math.cos(t));  
  29.                     y0 = (int) Math.round(y - r * Math.sin(t));  
  30.                     if (x0 < width && x0 > 0 && y0 < height && y0 > 0) {  
  31.                         acc[x0 + (y0 * width)] += 1;  
  32.                     }  
  33.                 }  
  34.             }  
  35.         }  
  36.     }  
  37.   
  38.     // now normalise to 255 and put in format for a pixel array  
  39.     int max = 0;  
  40.   
  41.     // Find max acc value  
  42.     for (int x = 0; x < width; x++) {  
  43.         for (int y = 0; y < height; y++) {  
  44.   
  45.             if (acc[x + (y * width)] > max) {  
  46.                 max = acc[x + (y * width)];  
  47.             }  
  48.         }  
  49.     }  
  50.   
  51.     // 根据最大值,实现极坐标空间的灰度值归一化处理  
  52.     int value;  
  53.     for (int x = 0; x < width; x++) {  
  54.         for (int y = 0; y < height; y++) {  
  55.             value = (int) (((double) acc[x + (y * width)] / (double) max) * 255.0);  
  56.             acc[x + (y * width)] = 0xff000000 | (value << 16 | value << 8 | value);  
  57.         }  
  58.     }  
  59.       
  60.     // 绘制发现的圆  
  61.     findMaxima();  
  62.     System.out.println("done");  
  63.     return output;  
  64. }  
完整的算法源代码, 已经全部的加上注释
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.gloomyfish.image.transform.hough;  
  2. /*** 
  3.  *  
  4.  * 传入的图像为二值图像,背景为黑色,目标前景颜色为为白色 
  5.  * @author gloomyfish 
  6.  *  
  7.  */  
  8. public class CircleHough {  
  9.   
  10.     private int[] input;  
  11.     private int[] output;  
  12.     private int width;  
  13.     private int height;  
  14.     private int[] acc;  
  15.     private int accSize = 1;  
  16.     private int[] results;  
  17.     private int r; // 圆周的半径大小  
  18.   
  19.     public CircleHough() {  
  20.         System.out.println("Hough Circle Detection...");  
  21.     }  
  22.   
  23.     public void init(int[] inputIn, int widthIn, int heightIn, int radius) {  
  24.         r = radius;  
  25.         width = widthIn;  
  26.         height = heightIn;  
  27.         input = new int[width * height];  
  28.         output = new int[width * height];  
  29.         input = inputIn;  
  30.         for (int y = 0; y < height; y++) {  
  31.             for (int x = 0; x < width; x++) {  
  32.                 output[x + (width * y)] = 0xff000000//默认图像背景颜色为黑色  
  33.             }  
  34.         }  
  35.     }  
  36.   
  37.     public void setCircles(int circles) {  
  38.         accSize = circles; // 检测的个数  
  39.     }  
  40.       
  41.     /** 
  42.      * 霍夫变换处理 - 检测半径大小符合的圆的个数 
  43.      * 1. 将图像像素从2D空间坐标转换到极坐标空间 
  44.      * 2. 在极坐标空间中归一化各个点强度,使之在0〜255之间 
  45.      * 3. 根据极坐标的R值与输入参数(圆的半径)相等,寻找2D空间的像素点 
  46.      * 4. 对找出的空间像素点赋予结果颜色(红色) 
  47.      * 5. 返回结果2D空间像素集合 
  48.      * @return int [] 
  49.      */  
  50.     public int[] process() {  
  51.   
  52.         // 对于圆的极坐标变换来说,我们需要360度的空间梯度叠加值  
  53.         acc = new int[width * height];  
  54.         for (int y = 0; y < height; y++) {  
  55.             for (int x = 0; x < width; x++) {  
  56.                 acc[y * width + x] = 0;  
  57.             }  
  58.         }  
  59.         int x0, y0;  
  60.         double t;  
  61.         for (int x = 0; x < width; x++) {  
  62.             for (int y = 0; y < height; y++) {  
  63.   
  64.                 if ((input[y * width + x] & 0xff) == 255) {  
  65.   
  66.                     for (int theta = 0; theta < 360; theta++) {  
  67.                         t = (theta * 3.14159265) / 180// 角度值0 ~ 2*PI  
  68.                         x0 = (int) Math.round(x - r * Math.cos(t));  
  69.                         y0 = (int) Math.round(y - r * Math.sin(t));  
  70.                         if (x0 < width && x0 > 0 && y0 < height && y0 > 0) {  
  71.                             acc[x0 + (y0 * width)] += 1;  
  72.                         }  
  73.                     }  
  74.                 }  
  75.             }  
  76.         }  
  77.   
  78.         // now normalise to 255 and put in format for a pixel array  
  79.         int max = 0;  
  80.   
  81.         // Find max acc value  
  82.         for (int x = 0; x < width; x++) {  
  83.             for (int y = 0; y < height; y++) {  
  84.   
  85.                 if (acc[x + (y * width)] > max) {  
  86.                     max = acc[x + (y * width)];  
  87.                 }  
  88.             }  
  89.         }  
  90.   
  91.         // 根据最大值,实现极坐标空间的灰度值归一化处理  
  92.         int value;  
  93.         for (int x = 0; x < width; x++) {  
  94.             for (int y = 0; y < height; y++) {  
  95.                 value = (int) (((double) acc[x + (y * width)] / (double) max) * 255.0);  
  96.                 acc[x + (y * width)] = 0xff000000 | (value << 16 | value << 8 | value);  
  97.             }  
  98.         }  
  99.           
  100.         // 绘制发现的圆  
  101.         findMaxima();  
  102.         System.out.println("done");  
  103.         return output;  
  104.     }  
  105.   
  106.     private int[] findMaxima() {  
  107.         results = new int[accSize * 3];  
  108.         int[] output = new int[width * height];  
  109.           
  110.         // 获取最大的前accSize个值  
  111.         for (int x = 0; x < width; x++) {  
  112.             for (int y = 0; y < height; y++) {  
  113.                 int value = (acc[x + (y * width)] & 0xff);  
  114.   
  115.                 // if its higher than lowest value add it and then sort  
  116.                 if (value > results[(accSize - 1) * 3]) {  
  117.   
  118.                     // add to bottom of array  
  119.                     results[(accSize - 1) * 3] = value; //像素值  
  120.                     results[(accSize - 1) * 3 + 1] = x; // 坐标X  
  121.                     results[(accSize - 1) * 3 + 2] = y; // 坐标Y  
  122.   
  123.                     // shift up until its in right place  
  124.                     int i = (accSize - 2) * 3;  
  125.                     while ((i >= 0) && (results[i + 3] > results[i])) {  
  126.                         for (int j = 0; j < 3; j++) {  
  127.                             int temp = results[i + j];  
  128.                             results[i + j] = results[i + 3 + j];  
  129.                             results[i + 3 + j] = temp;  
  130.                         }  
  131.                         i = i - 3;  
  132.                         if (i < 0)  
  133.                             break;  
  134.                     }  
  135.                 }  
  136.             }  
  137.         }  
  138.   
  139.         // 根据找到的半径R,中心点像素坐标p(x, y),绘制圆在原图像上  
  140.         System.out.println("top " + accSize + " matches:");  
  141.         for (int i = accSize - 1; i >= 0; i--) {  
  142.             drawCircle(results[i * 3], results[i * 3 + 1], results[i * 3 + 2]);  
  143.         }  
  144.         return output;  
  145.     }  
  146.   
  147.     private void setPixel(int value, int xPos, int yPos) {  
  148.         /// output[(yPos * width) + xPos] = 0xff000000 | (value << 16 | value << 8 | value);  
  149.         output[(yPos * width) + xPos] = 0xffff0000;  
  150.     }  
  151.   
  152.     // draw circle at x y  
  153.     private void drawCircle(int pix, int xCenter, int yCenter) {  
  154.         pix = 250// 颜色值,默认为白色  
  155.   
  156.         int x, y, r2;  
  157.         int radius = r;  
  158.         r2 = r * r;  
  159.           
  160.         // 绘制圆的上下左右四个点  
  161.         setPixel(pix, xCenter, yCenter + radius);  
  162.         setPixel(pix, xCenter, yCenter - radius);  
  163.         setPixel(pix, xCenter + radius, yCenter);  
  164.         setPixel(pix, xCenter - radius, yCenter);  
  165.   
  166.         y = radius;  
  167.         x = 1;  
  168.         y = (int) (Math.sqrt(r2 - 1) + 0.5);  
  169.           
  170.         // 边缘填充算法, 其实可以直接对循环所有像素,计算到做中心点距离来做  
  171.         // 这个方法是别人写的,发现超赞,超好!  
  172.         while (x < y) {  
  173.             setPixel(pix, xCenter + x, yCenter + y);  
  174.             setPixel(pix, xCenter + x, yCenter - y);  
  175.             setPixel(pix, xCenter - x, yCenter + y);  
  176.             setPixel(pix, xCenter - x, yCenter - y);  
  177.             setPixel(pix, xCenter + y, yCenter + x);  
  178.             setPixel(pix, xCenter + y, yCenter - x);  
  179.             setPixel(pix, xCenter - y, yCenter + x);  
  180.             setPixel(pix, xCenter - y, yCenter - x);  
  181.             x += 1;  
  182.             y = (int) (Math.sqrt(r2 - x * x) + 0.5);  
  183.         }  
  184.         if (x == y) {  
  185.             setPixel(pix, xCenter + x, yCenter + y);  
  186.             setPixel(pix, xCenter + x, yCenter - y);  
  187.             setPixel(pix, xCenter - x, yCenter + y);  
  188.             setPixel(pix, xCenter - x, yCenter - y);  
  189.         }  
  190.     }  
  191.   
  192.     public int[] getAcc() {  
  193.         return acc;  
  194.     }  
  195.   
  196. }  
测试的UI类:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.gloomyfish.image.transform.hough;  
  2.   
  3. import java.awt.BorderLayout;  
  4. import java.awt.Color;  
  5. import java.awt.Dimension;  
  6. import java.awt.FlowLayout;  
  7. import java.awt.Graphics;  
  8. import java.awt.Graphics2D;  
  9. import java.awt.GridLayout;  
  10. import java.awt.event.ActionEvent;  
  11. import java.awt.event.ActionListener;  
  12. import java.awt.image.BufferedImage;  
  13. import java.io.File;  
  14.   
  15. import javax.imageio.ImageIO;  
  16. import javax.swing.BorderFactory;  
  17. import javax.swing.JButton;  
  18. import javax.swing.JFrame;  
  19. import javax.swing.JPanel;  
  20. import javax.swing.JSlider;  
  21. import javax.swing.event.ChangeEvent;  
  22. import javax.swing.event.ChangeListener;  
  23.   
  24. public class HoughUI extends JFrame implements ActionListener, ChangeListener {  
  25.     /** 
  26.      *  
  27.      */  
  28.     public static final String CMD_LINE = "Line Detection";  
  29.     public static final String CMD_CIRCLE = "Circle Detection";  
  30.     private static final long serialVersionUID = 1L;  
  31.     private BufferedImage sourceImage;  
  32. //  private BufferedImage houghImage;  
  33.     private BufferedImage resultImage;  
  34.     private JButton lineBtn;  
  35.     private JButton circleBtn;  
  36.     private JSlider radiusSlider;  
  37.     private JSlider numberSlider;  
  38.     public HoughUI(String imagePath)  
  39.     {  
  40.         super("GloomyFish-Image Process Demo");  
  41.         try{  
  42.             File file = new File(imagePath);  
  43.             sourceImage = ImageIO.read(file);  
  44.         } catch(Exception e){  
  45.             e.printStackTrace();  
  46.         }  
  47.         initComponent();  
  48.     }  
  49.       
  50.     private void initComponent() {  
  51.         int RADIUS_MIN = 1;  
  52.         int RADIUS_INIT = 1;  
  53.         int RADIUS_MAX = 51;  
  54.         lineBtn = new JButton(CMD_LINE);  
  55.         circleBtn = new JButton(CMD_CIRCLE);  
  56.         radiusSlider = new JSlider(JSlider.HORIZONTAL, RADIUS_MIN, RADIUS_MAX, RADIUS_INIT);  
  57.         radiusSlider.setMajorTickSpacing(10);  
  58.         radiusSlider.setMinorTickSpacing(1);  
  59.         radiusSlider.setPaintTicks(true);  
  60.         radiusSlider.setPaintLabels(true);  
  61.         numberSlider = new JSlider(JSlider.HORIZONTAL, RADIUS_MIN, RADIUS_MAX, RADIUS_INIT);  
  62.         numberSlider.setMajorTickSpacing(10);  
  63.         numberSlider.setMinorTickSpacing(1);  
  64.         numberSlider.setPaintTicks(true);  
  65.         numberSlider.setPaintLabels(true);  
  66.           
  67.         JPanel sliderPanel = new JPanel();  
  68.         sliderPanel.setLayout(new GridLayout(12));  
  69.         sliderPanel.setBorder(BorderFactory.createTitledBorder("Settings:"));  
  70.         sliderPanel.add(radiusSlider);  
  71.         sliderPanel.add(numberSlider);  
  72.         JPanel btnPanel = new JPanel();  
  73.         btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));  
  74.         btnPanel.add(lineBtn);  
  75.         btnPanel.add(circleBtn);  
  76.           
  77.           
  78.         JPanel imagePanel = new JPanel(){  
  79.   
  80.             private static final long serialVersionUID = 1L;  
  81.   
  82.             protected void paintComponent(Graphics g) {  
  83.                 if(sourceImage != null)  
  84.                 {  
  85.                     Graphics2D g2 = (Graphics2D) g;  
  86.                     g2.drawImage(sourceImage, 1010, sourceImage.getWidth(), sourceImage.getHeight(),null);  
  87.                     g2.setPaint(Color.BLUE);  
  88.                     g2.drawString("原图"10, sourceImage.getHeight() + 30);  
  89.                     if(resultImage != null)  
  90.                     {  
  91.                         g2.drawImage(resultImage, resultImage.getWidth() + 2010, resultImage.getWidth(), resultImage.getHeight(), null);  
  92.                         g2.drawString("最终结果,红色是检测结果", resultImage.getWidth() + 40, sourceImage.getHeight() + 30);  
  93.                     }  
  94.                 }  
  95.             }  
  96.               
  97.         };  
  98.         this.getContentPane().setLayout(new BorderLayout());  
  99.         this.getContentPane().add(sliderPanel, BorderLayout.NORTH);  
  100.         this.getContentPane().add(btnPanel, BorderLayout.SOUTH);  
  101.         this.getContentPane().add(imagePanel, BorderLayout.CENTER);  
  102.           
  103.         // setup listener  
  104.         this.lineBtn.addActionListener(this);  
  105.         this.circleBtn.addActionListener(this);  
  106.         this.numberSlider.addChangeListener(this);  
  107.         this.radiusSlider.addChangeListener(this);  
  108.     }  
  109.       
  110.     public static void main(String[] args)  
  111.     {  
  112.         String filePath = System.getProperty ("user.home") + "/Desktop/" + "zhigang/hough-test.png";  
  113.         HoughUI frame = new HoughUI(filePath);  
  114.         // HoughUI frame = new HoughUI("D:\\image-test\\lines.png");  
  115.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  116.         frame.setPreferredSize(new Dimension(800600));  
  117.         frame.pack();  
  118.         frame.setVisible(true);  
  119.     }  
  120.   
  121.     @Override  
  122.     public void actionPerformed(ActionEvent e) {  
  123.         if(e.getActionCommand().equals(CMD_LINE))  
  124.         {  
  125.             HoughFilter filter = new HoughFilter(HoughFilter.LINE_TYPE);  
  126.             resultImage = filter.filter(sourceImage, null);  
  127.             this.repaint();  
  128.         }  
  129.         else if(e.getActionCommand().equals(CMD_CIRCLE))  
  130.         {  
  131.             HoughFilter filter = new HoughFilter(HoughFilter.CIRCLE_TYPE);  
  132.             resultImage = filter.filter(sourceImage, null);  
  133.             // resultImage = filter.getHoughSpaceImage(sourceImage, null);  
  134.             this.repaint();  
  135.         }  
  136.           
  137.     }  
  138.   
  139.     @Override  
  140.     public void stateChanged(ChangeEvent e) {  
  141.         // TODO Auto-generated method stub  
  142.           
  143.     }  
  144. }  
五:霍夫变换检测圆与直线的图像预处理

使用霍夫变换检测圆与直线时候,一定要对图像进行预处理,灰度化以后,提取

图像的边缘使用非最大信号压制得到一个像素宽的边缘, 这个步骤对霍夫变

换非常重要.否则可能导致霍夫变换检测的严重失真.

第一次用Mac发博文,编辑不好请见谅!

1 0