圖像處理之霍夫變換圓檢測算法
之前寫過一篇文章講述霍夫變換原理與利用霍夫變換檢測直線, 結果發現訪問量還是蠻
多,有點超出我的意料,很多人都留言說代碼寫得不好,沒有注釋,結構也不是很清晰,所以
我萌發了再寫一篇,介紹霍夫變換圓檢測算法,同時也盡量的加上詳細的注釋,介紹代碼
結構.讓更多的人能夠讀懂與理解.
一:霍夫變換檢測圓的數學原理

根據極坐標,圓上任意一點的坐標可以表示為如上形式, 所以對於任意一個圓, 假設
中心像素點p(x0, y0)像素點已知, 圓半徑已知,則旋轉360由極坐標方程可以得到每
個點上得坐標同樣,如果只是知道圖像上像素點, 圓半徑,旋轉360°則中心點處的坐
標值必定最強.這正是霍夫變換檢測圓的數學原理.
二:算法流程
該算法大致可以分為以下幾個步驟
三:運行效果
圖像從空間坐標變換到極坐標效果, 最亮一點為圓心.
圖像從極坐標變換回到空間坐標,檢測結果顯示:

四:關鍵代碼解析
個人覺得這次注釋已經是非常的詳細啦,而且我寫的還是中文注釋
/**
* 霍夫變換處理 - 檢測半徑大小符合的圓的個數
* 1. 將圖像像素從2D空間坐標轉換到極坐標空間
* 2. 在極坐標空間中歸一化各個點強度,使之在0〜255之間
* 3. 根據極坐標的R值與輸入參數(圓的半徑)相等,尋找2D空間的像素點
* 4. 對找出的空間像素點賦予結果顏色(紅色)
* 5. 返回結果2D空間像素集合
* @return int []
*/
public int[] process() {
// 對於圓的極坐標變換來說,我們需要360度的空間梯度疊加值
acc = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
acc[y * width + x] = 0;
}
}
int x0, y0;
double t;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if ((input[y * width + x] & 0xff) == 255) {
for (int theta = 0; theta < 360; theta++) {
t = (theta * 3.14159265) / 180; // 角度值0 ~ 2*PI
x0 = (int) Math.round(x - r * Math.cos(t));
y0 = (int) Math.round(y - r * Math.sin(t));
if (x0 < width && x0 > 0 && y0 < height && y0 > 0) {
acc[x0 + (y0 * width)] += 1;
}
}
}
}
}
// now normalise to 255 and put in format for a pixel array
int max = 0;
// Find max acc value
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (acc[x + (y * width)] > max) {
max = acc[x + (y * width)];
}
}
}
// 根據最大值,實現極坐標空間的灰度值歸一化處理
int value;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
value = (int) (((double) acc[x + (y * width)] / (double) max) * 255.0);
acc[x + (y * width)] = 0xff000000 | (value << 16 | value << 8 | value);
}
}
// 繪制發現的圓
findMaxima();
System.out.println("done");
return output;
}
完整的算法源代碼, 已經全部的加上注釋
package com.gloomyfish.image.transform.hough;
/***
*
* 傳入的圖像為二值圖像,背景為黑色,目標前景顏色為為白色
* @author gloomyfish
*
*/
public class CircleHough {
private int[] input;
private int[] output;
private int width;
private int height;
private int[] acc;
private int accSize = 1;
private int[] results;
private int r; // 圓周的半徑大小
public CircleHough() {
System.out.println("Hough Circle Detection...");
}
public void init(int[] inputIn, int widthIn, int heightIn, int radius) {
r = radius;
width = widthIn;
height = heightIn;
input = new int[width * height];
output = new int[width * height];
input = inputIn;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
output[x + (width * y)] = 0xff000000; //默認圖像背景顏色為黑色
}
}
}
public void setCircles(int circles) {
accSize = circles; // 檢測的個數
}
/**
* 霍夫變換處理 - 檢測半徑大小符合的圓的個數
* 1. 將圖像像素從2D空間坐標轉換到極坐標空間
* 2. 在極坐標空間中歸一化各個點強度,使之在0〜255之間
* 3. 根據極坐標的R值與輸入參數(圓的半徑)相等,尋找2D空間的像素點
* 4. 對找出的空間像素點賦予結果顏色(紅色)
* 5. 返回結果2D空間像素集合
* @return int []
*/
public int[] process() {
// 對於圓的極坐標變換來說,我們需要360度的空間梯度疊加值
acc = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
acc[y * width + x] = 0;
}
}
int x0, y0;
double t;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if ((input[y * width + x] & 0xff) == 255) {
for (int theta = 0; theta < 360; theta++) {
t = (theta * 3.14159265) / 180; // 角度值0 ~ 2*PI
x0 = (int) Math.round(x - r * Math.cos(t));
y0 = (int) Math.round(y - r * Math.sin(t));
if (x0 < width && x0 > 0 && y0 < height && y0 > 0) {
acc[x0 + (y0 * width)] += 1;
}
}
}
}
}
// now normalise to 255 and put in format for a pixel array
int max = 0;
// Find max acc value
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (acc[x + (y * width)] > max) {
max = acc[x + (y * width)];
}
}
}
// 根據最大值,實現極坐標空間的灰度值歸一化處理
int value;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
value = (int) (((double) acc[x + (y * width)] / (double) max) * 255.0);
acc[x + (y * width)] = 0xff000000 | (value << 16 | value << 8 | value);
}
}
// 繪制發現的圓
findMaxima();
System.out.println("done");
return output;
}
private int[] findMaxima() {
results = new int[accSize * 3];
int[] output = new int[width * height];
// 獲取最大的前accSize個值
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int value = (acc[x + (y * width)] & 0xff);
// if its higher than lowest value add it and then sort
if (value > results[(accSize - 1) * 3]) {
// add to bottom of array
results[(accSize - 1) * 3] = value; //像素值
results[(accSize - 1) * 3 + 1] = x; // 坐標X
results[(accSize - 1) * 3 + 2] = y; // 坐標Y
// shift up until its in right place
int i = (accSize - 2) * 3;
while ((i >= 0) && (results[i + 3] > results[i])) {
for (int j = 0; j < 3; j++) {
int temp = results[i + j];
results[i + j] = results[i + 3 + j];
results[i + 3 + j] = temp;
}
i = i - 3;
if (i < 0)
break;
}
}
}
}
// 根據找到的半徑R,中心點像素坐標p(x, y),繪制圓在原圖像上
System.out.println("top " + accSize + " matches:");
for (int i = accSize - 1; i >= 0; i--) {
drawCircle(results[i * 3], results[i * 3 + 1], results[i * 3 + 2]);
}
return output;
}
private void setPixel(int value, int xPos, int yPos) {
/// output[(yPos * width) + xPos] = 0xff000000 | (value << 16 | value << 8 | value);
output[(yPos * width) + xPos] = 0xffff0000;
}
// draw circle at x y
private void drawCircle(int pix, int xCenter, int yCenter) {
pix = 250; // 顏色值,默認為白色
int x, y, r2;
int radius = r;
r2 = r * r;
// 繪制圓的上下左右四個點
setPixel(pix, xCenter, yCenter + radius);
setPixel(pix, xCenter, yCenter - radius);
setPixel(pix, xCenter + radius, yCenter);
setPixel(pix, xCenter - radius, yCenter);
y = radius;
x = 1;
y = (int) (Math.sqrt(r2 - 1) + 0.5);
// 邊緣填充算法, 其實可以直接對循環所有像素,計算到做中心點距離來做
// 這個方法是別人寫的,發現超贊,超好!
while (x < y) {
setPixel(pix, xCenter + x, yCenter + y);
setPixel(pix, xCenter + x, yCenter - y);
setPixel(pix, xCenter - x, yCenter + y);
setPixel(pix, xCenter - x, yCenter - y);
setPixel(pix, xCenter + y, yCenter + x);
setPixel(pix, xCenter + y, yCenter - x);
setPixel(pix, xCenter - y, yCenter + x);
setPixel(pix, xCenter - y, yCenter - x);
x += 1;
y = (int) (Math.sqrt(r2 - x * x) + 0.5);
}
if (x == y) {
setPixel(pix, xCenter + x, yCenter + y);
setPixel(pix, xCenter + x, yCenter - y);
setPixel(pix, xCenter - x, yCenter + y);
setPixel(pix, xCenter - x, yCenter - y);
}
}
public int[] getAcc() {
return acc;
}
}
測試的UI類:
package com.gloomyfish.image.transform.hough;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class HoughUI extends JFrame implements ActionListener, ChangeListener {
/**
*
*/
public static final String CMD_LINE = "Line Detection";
public static final String CMD_CIRCLE = "Circle Detection";
private static final long serialVersionUID = 1L;
private BufferedImage sourceImage;
// private BufferedImage houghImage;
private BufferedImage resultImage;
private JButton lineBtn;
private JButton circleBtn;
private JSlider radiusSlider;
private JSlider numberSlider;
public HoughUI(String imagePath)
{
super("GloomyFish-Image Process Demo");
try{
File file = new File(imagePath);
sourceImage = ImageIO.read(file);
} catch(Exception e){
e.printStackTrace();
}
initComponent();
}
private void initComponent() {
int RADIUS_MIN = 1;
int RADIUS_INIT = 1;
int RADIUS_MAX = 51;
lineBtn = new JButton(CMD_LINE);
circleBtn = new JButton(CMD_CIRCLE);
radiusSlider = new JSlider(JSlider.HORIZONTAL, RADIUS_MIN, RADIUS_MAX, RADIUS_INIT);
radiusSlider.setMajorTickSpacing(10);
radiusSlider.setMinorTickSpacing(1);
radiusSlider.setPaintTicks(true);
radiusSlider.setPaintLabels(true);
numberSlider = new JSlider(JSlider.HORIZONTAL, RADIUS_MIN, RADIUS_MAX, RADIUS_INIT);
numberSlider.setMajorTickSpacing(10);
numberSlider.setMinorTickSpacing(1);
numberSlider.setPaintTicks(true);
numberSlider.setPaintLabels(true);
JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new GridLayout(1, 2));
sliderPanel.setBorder(BorderFactory.createTitledBorder("Settings:"));
sliderPanel.add(radiusSlider);
sliderPanel.add(numberSlider);
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
btnPanel.add(lineBtn);
btnPanel.add(circleBtn);
JPanel imagePanel = new JPanel(){
private static final long serialVersionUID = 1L;
protected void paintComponent(Graphics g) {
if(sourceImage != null)
{
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(sourceImage, 10, 10, sourceImage.getWidth(), sourceImage.getHeight(),null);
g2.setPaint(Color.BLUE);
g2.drawString("原圖", 10, sourceImage.getHeight() + 30);
if(resultImage != null)
{
g2.drawImage(resultImage, resultImage.getWidth() + 20, 10, resultImage.getWidth(), resultImage.getHeight(), null);
g2.drawString("最終結果,紅色是檢測結果", resultImage.getWidth() + 40, sourceImage.getHeight() + 30);
}
}
}
};
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(sliderPanel, BorderLayout.NORTH);
this.getContentPane().add(btnPanel, BorderLayout.SOUTH);
this.getContentPane().add(imagePanel, BorderLayout.CENTER);
// setup listener
this.lineBtn.addActionListener(this);
this.circleBtn.addActionListener(this);
this.numberSlider.addChangeListener(this);
this.radiusSlider.addChangeListener(this);
}
public static void main(String[] args)
{
String filePath = System.getProperty ("user.home") + "/Desktop/" + "zhigang/hough-test.png";
HoughUI frame = new HoughUI(filePath);
// HoughUI frame = new HoughUI("D:\\image-test\\lines.png");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals(CMD_LINE))
{
HoughFilter filter = new HoughFilter(HoughFilter.LINE_TYPE);
resultImage = filter.filter(sourceImage, null);
this.repaint();
}
else if(e.getActionCommand().equals(CMD_CIRCLE))
{
HoughFilter filter = new HoughFilter(HoughFilter.CIRCLE_TYPE);
resultImage = filter.filter(sourceImage, null);
// resultImage = filter.getHoughSpaceImage(sourceImage, null);
this.repaint();
}
}
@Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
}
}
五:霍夫變換檢測圓與直線的圖像預處理
使用霍夫變換檢測圓與直線時候,一定要對圖像進行預處理,灰度化以后,提取
圖像的邊緣使用非最大信號壓制得到一個像素寬的邊緣, 這個步驟對霍夫變
換非常重要.否則可能導致霍夫變換檢測的嚴重失真.
第一次用Mac發博文,編輯不好請見諒!
