圖像處理之霍夫變換圓檢測算法

圖像處理之霍夫變換圓檢測算法

之前寫過一篇文章講述霍夫變換原理與利用霍夫變換檢測直線, 結果發現訪問量還是蠻

多,有點超出我的意料,很多人都留言說代碼寫得不好,沒有註釋,結構也不是很清晰,所以

我萌發了再寫一篇,介紹霍夫變換圓檢測算法,同時也儘量的加上詳細的註釋,介紹代碼

結構.讓更多的人能夠讀懂與理解.

一:霍夫變換檢測圓的數學原理


根據極座標,圓上任意一點的座標可以表示爲如上形式, 所以對於任意一個圓, 假設

中心像素點p(x0, y0)像素點已知, 圓半徑已知,則旋轉360由極座標方程可以得到每

個點上得座標同樣,如果只是知道圖像上像素點, 圓半徑,旋轉360°則中心點處的坐

標值必定最強.這正是霍夫變換檢測圓的數學原理.

二:算法流程

該算法大致可以分爲以下幾個步驟


三:運行效果

圖像從空間座標變換到極座標效果, 最亮一點爲圓心.


圖像從極座標變換回到空間座標,檢測結果顯示:


四:關鍵代碼解析

個人覺得這次註釋已經是非常的詳細啦,而且我寫的還是中文註釋

[java] view plain copy
  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 plain copy
  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 plain copy
  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發博文,編輯不好請見諒!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章