윤곽선(Contour)은 특정 형태의 경계를 따라 있는 모든 점을 연결한 선을 의미합니다. 윤곽선을 활용하면 다음과 같은 작업을 수행할 수 있습니다.
- 객체의 형태(shape) 파악
- 객체의 면적(area) 계산
- 객체 탐지(detection)
- 객체 인식(recognition)
이미지 내의 다양한 도형이나 객체의 윤곽선은 OpenCV의 findContours() 메서드를 사용하여 찾을 수 있습니다. 이 메서드는 다음과 같은 매개변수를 받습니다.
- 이진화(binary)된 이미지 — 윤곽선 검출의 대상이 되는 흑백 이미지입니다.
- 윤곽선 정보를 저장할
MatOfPoint타입의 빈 리스트 객체 - 이미지 토폴로지(위계 정보)를 저장할 빈 Mat 객체
- 윤곽선 검출 모드(mode)와 방식(method)을 지정하는 두 개의 정수형 변수
예제 코드
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);
// 윤곽선 그리기
Imgproc.drawContours(draw, contours, i, color, 2, Imgproc.LINE_8, hierarchey, 2, new Point() ) ;
}
HighGui.imshow("Contours operation", draw);
HighGui.waitKey();
*/
}
}코드 설명
위 예제는 다음 순서로 동작합니다.
System.loadLibrary()를 호출하여 OpenCV 네이티브 라이브러리를 로드합니다.Imgcodecs.imread()로 이미지 파일을 읽어옵니다.cvtColor()메서드로 컬러 이미지를 그레이스케일로 변환합니다.threshold()메서드에THRESH_BINARY_INV옵션을 지정해 이미지를 이진화합니다.findContours()메서드에RETR_TREE(모든 윤곽선의 전체 위계 구조 검색)와CHAIN_APPROX_SIMPLE(수평·수직·대각선 세그먼트의 끝점만 저장하여 메모리 절약) 옵션을 적용해 윤곽선을 추출합니다.- 검출된 각 윤곽선을 반복자(iterator)로 순회하며 출력합니다.
실행 결과
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 ]
출력 결과에서 각 Mat 객체는 하나의 윤곽선을 나타내며, 행 크기(예: 29, 58, 117 등)는 해당 윤곽선을 구성하는 좌표점의 개수를 의미합니다. 주석 처리된 코드 부분의 주석을 해제하면 drawContours()와 HighGui를 활용해 검출된 윤곽선을 빨간색 선으로 화면에 직접 시각화할 수도 있습니다.