12회차 수업 끝

This commit is contained in:
USW
2025-05-07 12:06:35 +09:00
parent 63525bab64
commit 0d9c3ed470
9 changed files with 562 additions and 0 deletions

61
ch12/labeling/main.cpp Normal file
View File

@@ -0,0 +1,61 @@
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace cv;
void labeling_basic() {
uchar data[] = {
0, 0, 1, 1, 0, 0, 0, 0,
1, 1, 1, 1, 0, 0, 1, 0,
1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 0,
0, 0, 0, 1, 1, 1, 1, 0,
0, 0, 0, 1, 0, 0, 1, 0,
0, 0, 1, 1, 1, 1, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
Mat src = Mat(8, 8, CV_8UC1, data) * 255;
Mat labels;
int cnt = connectedComponents(src, labels);
std::cout << "src:\n" << src << std::endl;
std::cout << "lables:\n" << labels << std::endl;
std::cout << "number of lables:\n" << cnt << std::endl;
}
void labling_stats() {
Mat src = imread("../../resources/images/keyboard.bmp", IMREAD_GRAYSCALE);
Mat bin;
threshold(src, bin, 0, 255, THRESH_BINARY | THRESH_OTSU);
Mat labels, stats, centroids;
int cnt = connectedComponentsWithStats(bin, labels, stats, centroids);
Mat dst;
cvtColor(src, dst, COLOR_GRAY2BGR);
for (int i = 1; i < cnt; i++) {
int* p = stats.ptr<int>(i);
double* c = centroids.ptr<double>(i);
//if (p[4] < 20)
// continue;
rectangle(dst, Rect(p[0], p[1], p[2], p[3]), Scalar(0, 255, 255), 2);
char num[30] = { '0' + i, '\0'};
sprintf_s(num, "%d", i);
putText(dst, num, Point(c[0], c[1]), FONT_HERSHEY_PLAIN, 1.2, Scalar(0, 0, 255));
}
imshow("src", src);
imshow("dst", dst);
waitKey();
destroyAllWindows();
}
int main() {
labling_stats();
}