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

  /**
* 霍夫变换处理 - 检测半径大小符合的圆的个数
* 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) {
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;
r2 = r * r;

// 绘制圆的上下左右四个点

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;
}

}

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 numberSlider;
public HoughUI(String imagePath)
{
super("GloomyFish-Image Process Demo");
try{
File file = new File(imagePath);
} catch(Exception e){
e.printStackTrace();
}
initComponent();
}

private void initComponent() {
lineBtn = new JButton(CMD_LINE);
circleBtn = new JButton(CMD_CIRCLE);
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:"));
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

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());

// setup listener
}

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

}
}

|
1天前
|

【7月更文第18天】目标检测，作为计算机视觉领域的核心任务之一，旨在识别图像或视频中特定对象的位置及其类别。这一技术在自动驾驶、视频监控、医疗影像分析等多个领域发挥着至关重要的作用。本文将深入浅出地介绍目标检测的基本概念、主流算法，并通过一个实际的代码示例，带您领略YOLOv5这一高效目标检测模型的魅力。
22 11
|
5天前
|

【7月更文挑战第13天】目标检测作为计算机视觉领域的重要研究方向，近年来在深度学习技术的推动下取得了显著进展。然而，面对复杂多变的实际应用场景，仍需不断研究和探索更加高效、鲁棒的目标检测算法。随着技术的不断发展和应用场景的不断拓展，相信目标检测算法将在更多领域发挥重要作用。
26 9
|
8天前
|

Python实现Prophet时间序列数据建模与异常值检测(Prophet算法)项目实战
Python实现Prophet时间序列数据建模与异常值检测(Prophet算法)项目实战
25 2
|
8天前
|

18 1
|
13天前
|

【7月更文挑战第2天】 💡💡💡创新点： 1）SPD-Conv特别是在处理低分辨率图像和小物体等更困难的任务时优势明显； 2）引入Wasserstein Distance Loss提升小目标检测能力； 3）YOLOv8中的Conv用cvpr2024中的DynamicConv代替；
66 3
|
10天前
|

Python基于局部离群因子LOF算法(LocalOutlierFactor)实现信用卡数据异常值检测项目实战
Python基于局部离群因子LOF算法(LocalOutlierFactor)实现信用卡数据异常值检测项目实战
25 0
|
10天前
|

Python基于孤立森林算法(IsolationForest)实现数据异常值检测项目实战
Python基于孤立森林算法(IsolationForest)实现数据异常值检测项目实战
36 0
|
23天前
|

12 0
|
28天前
|

**语音识别算法概览** MATLAB2022a中实现，结合MFCC与GRNN技术进行说话人身份检测。MFCC利用人耳感知特性提取语音频谱特征，GRNN作为非线性映射工具，擅长序列学习，确保高效识别。预加重、分帧、加窗、FFT、滤波器组、IDCT构成MFCC步骤，GRNN以其快速学习与鲁棒性处理不稳定数据。适用于多种领域。
39 0
|
29天前
|

17 0