등고선은 특정 모양의 경계를 따라 모든 점을 연결하는 선에 불과합니다. 이것을 사용하면 다음을 할 수 있습니다 -
-
물체의 모양을 찾습니다.
-
물체의 면적을 계산합니다.
-
물체를 감지합니다.
-
물체를 인식합니다.
findContours()를 사용하여 이미지에서 다양한 모양, 개체의 윤곽을 찾을 수 있습니다. 방법. 같은 방법으로 그릴 수 있습니다
주어진 입력 이미지에서 모양의 영역을 찾을 수도 있습니다. 그렇게 하려면 contourArea()를 호출해야 합니다. Imgproc 클래스의 메소드. 이 메서드는 특정 모양의 윤곽을 받아들이고 해당 영역을 찾아 반환합니다.
예
다음 Java 예제는 주어진 이미지에서 각 모양/객체의 영역을 찾고 5000보다 작은 영역을 빨간색으로 나머지는 흰색으로 모양의 윤곽선을 그립니다.
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.CvType;
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 FindContourArea {
public static void main(String args[]) throws Exception {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the contents of the image
String file ="D:\\Images\\javafx_graphical.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);
Mat draw = Mat.zeros(src.size(), CvType.CV_8UC3);
for (int i = 0; i < contours.size(); i++) {
Scalar color = new Scalar(0, 0, 255);
//Calculating the area
double cont_area = Imgproc.contourArea(contours.get(i));
System.out.println(cont_area);
if(cont_area>5000.0){
Imgproc.drawContours(draw, contours, i, color, 2,
Imgproc.LINE_8, hierarchey, 2, new Point() ) ;
} else {
color = new Scalar(255, 255, 255);
Imgproc.drawContours(draw, contours, i, color, 2, Imgproc.LINE_8,
hierarchey, 2, new Point() ) ;
}
}
HighGui.imshow("Contours operation", draw);
HighGui.waitKey();
}
} 입력 이미지
출력
4091.0 6336.0 189.0 6439.0 4903.0
위의 출력 외에도 위의 프로그램은 다음 창을 생성합니다. -
