如何使用Java OpenCV库绘制图像轮廓?
轮廓不过是连接特定形状边界上所有点的线。使用它你可以:
查找物体的形状。
计算物体的面积。
检测物体。
识别物体。
你可以使用 **findContours()** 方法找到图像中各种形状、物体的轮廓。同样,你可以绘制
你可以使用 **drawContours()** 方法绘制找到的图像轮廓,此方法接受以下参数:
一个空的 Mat 对象来存储结果图像。
一个包含找到的轮廓的列表对象。
一个整数,指定要绘制的轮廓(负值表示绘制所有轮廓)。
一个 Scalar 对象,指定轮廓的颜色。
一个整数,指定轮廓的粗细。
示例
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
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;
public class DrawingContours {
public static void main(String args[]) throws Exception {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
String file ="D:\Images\shapes.jpg";
Mat src = Imgcodecs.imread(file);
//Converting the source image to binary
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);
//Finding Contours
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchey = new Mat();
Imgproc.findContours(binary, contours, hierarchey, Imgproc.RETR_TREE,
Imgproc.CHAIN_APPROX_SIMPLE);
//Drawing the Contours
Scalar color = new Scalar(0, 0, 255);
Imgproc.drawContours(src, contours, -1, color, 2, Imgproc.LINE_8,
hierarchey, 2, new Point() ) ;
HighGui.imshow("Drawing Contours", src);
HighGui.waitKey();
}
}输入图像

输出
执行上述程序后,将生成以下窗口:

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP