OpenCV 4로 배우는 컴퓨터 비전과 머신 러닝 中
코드 12-4 계층 구조를 사용하는 외곽선 검출과 그리기
void contours_hier() {
Mat src = imread("contours.bmp", IMREAD_GRAYSCALE);
if (src.empty()) {
cerr << "Image load failed!" << endl;
return;
}
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(src, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
Mat dst;
cvtColor(src, dst, COLOR_GRAY2BGR);
for (int idx = 0; idx >= 0; idx = hierarchy[idx][0]) {
Scalar c(rand() & 255, rand() & 255, rand() & 255);
drawContours(dst, contours, idx, c,-1,LINE_8,hierarchy);
}
imshow("src", src);
imshow("dst", dst);
waitKey();
destroyAllWindows();
}
vector<vector<Point>> contours; vector<Vec4i> hierarchy; findContours(src, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
findContours() 함수 호출 시 hierarchy 인자를 전달하여 계층 정보를 받아옵니다.
for (int idx = 0; idx >= 0; idx = hierarchy[idx][0])
0번 외곽선부터 시작하여 계층 정보의 다음 외곽선으로 이동하면서 for 반복문을 수행합니다.
drawContours(dst, contours, idx, c,-1,LINE_8,hierarchy);
drawContours() 함수에 hierarchy 정보를 전달하여 외곽선을 그리도록 합니다. 선의 두께를 -1로 지정하였으므로 외곽선 내부를 지정한 색깔로 채웁니다.