如何使用 Java OpenCV 库查找图像轮廓?
javaobject oriented programmingprogramming更新于 2025/10/8 10:20:17
轮廓不过是连接特定形状边界上所有点的线。使用它您可以−
查找物体的形状。
计算物体的面积。
检测物体。
识别物体。
您可以使用 findContours() 方法在图像中找到各种形状、物体的轮廓。此方法接受以下参数 −
二进制图像。
一个空的 MatOfPoint 类型的列表对象,用于存储轮廓。
一个空的 Mat 对象,用于存储图像拓扑。
两个整数变量,用于指定查找给定图像轮廓的模式和方法。
示例
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class FindingContours {
public static void main(String args[]) throws Exception {
//加载 OpenCV 核心库
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
String file ="D:\Images\shapes.jpg";
Mat src = Imgcodecs.imread(file);
//将源图像转换为二进制
Mat gray = new Mat(src.rows(), src.cols(), src.type());
Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
Mat binary = new Mat(src.rows(), src.cols(), src.type(), new Scalar(0));
Imgproc.threshold(gray, binary, 100, 255, Imgproc.THRESH_BINARY_INV);
//查找轮廓
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchey = new Mat();
Imgproc.findContours(binary, contours, hierarchey, Imgproc.RETR_TREE,
Imgproc.CHAIN_APPROX_SIMPLE);
Iterator<MatOfPoint> it = contours.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
/*
Mat draw = Mat.zeros(binary.size(), CvType.CV_8UC3);
for (int i = 0; i < contours.size(); i++) {
System.out.println(contours);
Scalar color = new Scalar(0, 0, 255);
//Drawing Contours
Imgproc.drawContours(draw, contours, i, color, 2, Imgproc.LINE_8, hierarchey, 2, new Point() ) ;
}
HighGui.imshow("Contours operation", draw);
HighGui.waitKey();
*/
}
}
输出
Mat [ 29*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19829510, dataAddr=0x19826dc0 ] Mat [ 58*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19829580, dataAddr=0x19826f00 ] Mat [ 35*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19828be0, dataAddr=0x19827100 ] Mat [ 117*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19829190, dataAddr=0x19827280 ] Mat [ 1*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x198292e0, dataAddr=0xba8280 ] Mat [ 78*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19829350, dataAddr=0x19827680 ] Mat [ 63*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x198289b0, dataAddr=0x19827940 ] Mat [ 120*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19828e80, dataAddr=0x19827b80 ] Mat [ 4*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19829430, dataAddr=0xb84580 ] Mat [ 4*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19829120, dataAddr=0xb84440 ] Mat [ 136*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19828ef0, dataAddr=0x19827f80 ] Mat [ 120*1*CV_32SC2, isCont=true, isSubmat=false, nativeObj=0x19828b00, dataAddr=0x19828440 ]
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

