OpenCV 霍夫圆变换的 Java 实现。
javaobject oriented programmingprogramming更新于 2025/10/9 10:20:17
您可以使用霍夫圆变换检测给定图像中的圆。您可以使用 HoughCircles() 方法应用 霍夫圆变换,此方法接受以下参数 −
表示输入图像的 Mat 对象。
用于存储找到的圆的输出向量的 Mat 对象。
表示检测方法的整数变量。
两个双精度变量,表示累加器分辨率与图像分辨率的反比以及检测到的圆心之间的最小距离。
示例
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Stage;
public class HoughCircleTransform extends Application {
public void start(Stage stage) throws IOException {
//加载 OpenCV 核心库
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
String file ="D:\Images\compass.jpg";
Mat src = Imgcodecs.imread(file);
//将图像转换为灰色
Mat gray = new Mat();
Imgproc.cvtColor(src, gray, Imgproc.COLOR_RGBA2GRAY);
//模糊图像
Mat blur = new Mat();
Imgproc.medianBlur(gray, blur, 5);
//检测霍夫圆
Mat circles = new Mat();
Imgproc.HoughCircles(blur, circles, Imgproc.HOUGH_GRADIENT, Math.PI/180, 150);
for (int i = 0; i < circles.cols(); i++ ) {
double[] data = circles.get(0, i);
Point center = new Point(Math.round(data[0]), Math.round(data[1]));
// 圆心
Imgproc.circle(src, center, 1, new Scalar(0, 0, 255), 3, 8, 0 );
// 圆轮廓
int radius = (int) Math.round(data[2]);
Imgproc.circle(src, center, radius, new Scalar(0,0,255), 3, 8, 0 );
}
//将矩阵转换为 JavaFX 可写图像
Image img = HighGui.toBufferedImage(src);
WritableImage writableImage= SwingFXUtils.toFXImage((BufferedImage) img, null);
//设置图像视图
ImageView imageView = new ImageView(writableImage);
imageView.setX(10);
imageView.setY(10);
imageView.setFitWidth(575);
imageView.setPreserveRatio(true);
//设置场景对象
Group root = new Group(imageView);
Scene scene = new Scene(root, 595, 400);
stage.setTitle("Hough Circle Transform");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]) {
launch(args);
}
}
输入图片

输出
执行后,上述代码产生以下输出 −

相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

