#python
import cv2
import numpy as np
def contours_basic():
src = cv2.imread("D:\\projects\\SampleCode\\006939-master\\ch12\\findcts\\contours.bmp", cv2.IMREAD_GRAYSCALE)
if src is None:
print("Image load failed!")
return
contours, _ = cv2.findContours(src, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
dst = cv2.cvtColor(src, cv2.COLOR_GRAY2BGR)
for contour in contours:
color = tuple(np.random.randint(0, 256, 3).tolist())
cv2.drawContours(dst, [contour], -1, color, 2)
cv2.imshow("src", src)
cv2.imshow("dst", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
def contours_hier():
src = cv2.imread("D:\\projects\\SampleCode\\006939-master\\ch12\\findcts\\contours.bmp", cv2.IMREAD_GRAYSCALE)
if src is None:
print("Image load failed!")
return
contours, hierarchy = cv2.findContours(src, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
dst = cv2.cvtColor(src, cv2.COLOR_GRAY2BGR)
for idx, contour in enumerate(contours):
color = tuple(np.random.randint(0, 256, 3).tolist())
cv2.drawContours(dst, contours, idx, color, -1, cv2.LINE_8, hierarchy)
cv2.imshow("src", src)
cv2.imshow("dst", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
def main():
contours_basic()
contours_hier()
if __name__ == "__main__":
main()
// C++
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
void contours_basic();
void contours_hier();
int main(void)
{
contours_basic();
contours_hier();
return 0;
}
void contours_basic()
{
Mat src = imread("contours.bmp", IMREAD_GRAYSCALE);
if (src.empty()) {
cerr << "Image load failed!" << endl;
return;
}
vector<vector<Point>> contours;
findContours(src, contours, RETR_LIST, CHAIN_APPROX_NONE);
Mat dst;
cvtColor(src, dst, COLOR_GRAY2BGR);
for (int i = 0; i < contours.size(); i++) {
Scalar c(rand() & 255, rand() & 255, rand() & 255);
drawContours(dst, contours, i, c, 2);
}
imshow("src", src);
imshow("dst", dst);
waitKey(0);
destroyAllWindows();
}
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(0);
destroyAllWindows();
}
C++ Code 출처 : OpenCV 4로 배우는 컴퓨터 비전과 머신 러닝 - 황선규 저
'OpenCV' 카테고리의 다른 글
ch12 polygon (0) | 2024.05.21 |
---|---|
ch12 labeling (0) | 2024.05.21 |
ch11 threshold (0) | 2024.05.21 |
ch11 morphology (0) | 2024.05.21 |
ch11 adaptive (0) | 2024.05.21 |