opencv findcontours如何找到内轮廓 用java实现
时间: 2023-10-08 17:09:45 浏览: 47
使用OpenCV的Java API中的findContours方法可以找到轮廓。要找到内轮廓,需要先找到所有外部轮廓,然后在这些轮廓中找到子轮廓。
以下是一个示例代码,它将在图像中找到所有外部和内部轮廓,并将其绘制在输出图像上:
```
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import java.util.ArrayList;
import java.util.List;
public class FindContours {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Load image
Mat image = Imgcodecs.imread("input.jpg");
// Convert to grayscale
Mat gray = new Mat();
Imgproc.cvtColor(image, gray, Imgproc.COLOR_BGR2GRAY);
// Threshold image
Mat thresh = new Mat();
Imgproc.threshold(gray, thresh, 100, 255, Imgproc.THRESH_BINARY_INV);
// Find contours
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(thresh, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
// Draw contours
Mat output = new Mat();
image.copyTo(output);
for (int i = 0; i < contours.size(); i++) {
Imgproc.drawContours(output, contours, i, new Scalar(0, 0, 255), 2);
// Find inner contours
MatOfInt hull = new MatOfInt();
Imgproc.convexHull(contours.get(i), hull, false);
List<MatOfPoint> innerContours = new ArrayList<>();
if (hierarchy.get(0, i)[2] != -1) {
int inner = (int) hierarchy.get(0, i)[2];
while (inner != -1) {
innerContours.add(contours.get(inner));
inner = (int) hierarchy.get(0, inner)[0];
}
Imgproc.drawContours(output, innerContours, -1, new Scalar(0, 255, 0), 2);
}
}
// Save output image
Imgcodecs.imwrite("output.jpg", output);
}
}
```
在这个示例中,我们首先将输入图像转换为灰度图像,然后对其进行二值化处理,以便找到轮廓。我们使用findContours方法来找到所有轮廓,并将它们绘制在输出图像上。然后,我们迭代所有轮廓,查找每个轮廓的内部轮廓,并将它们绘制为绿色。最后,我们将输出图像保存为文件。