Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void labelObjects() {
- char fileName[MAX_PATH];
- Mat src;
- while (openFileDlg(fileName)) {
- src = imread(fileName, CV_LOAD_IMAGE_GRAYSCALE);
- Mat labels = Mat::zeros(src.rows, src.cols, CV_8UC1);
- uchar label = 0;
- for (int i = 1; i < src.rows - 1; i++) {
- for (int j = 1; j < src.cols - 1; j++) {
- if (src.at<uchar>(i, j) == 0 && labels.at<uchar>(i, j) == 0) {
- label++;
- std::queue<Point2i> Q;
- labels.at<uchar>(i, j) = label;
- Q.push(Point2i(j, i));
- while (!Q.empty()) {
- Point2i q = Q.front();
- Q.pop();
- int dj[8] = { -1, 0, 1, 1, 1, 0, -1, -1 };
- int di[8] = { -1, -1, -1, 0, 1, 1, 1, 0 };
- for (int k = 0; k < 8; k++) {
- int ii = q.y + di[k];
- int jj = q.x + dj[k];
- if (jj >= 0 && jj < src.cols) {
- if (ii >= 0 && ii < src.rows) {
- // traversarea in latime pentru componente conexe
- if (src.at<uchar>(ii, jj) == 0 && labels.at<uchar>(ii, jj) == 0) {
- labels.at<uchar>(ii, jj) = label;
- Q.push(Point2i(jj, ii));
- }
- }
- }
- } // for for neighbours
- } // for while
- } // if
- } // for j
- } // for i
- Mat dst = Mat::zeros(labels.rows, labels.cols, CV_8UC3);
- Vec3b color;
- std::default_random_engine gen;
- std::uniform_int_distribution<int> d(0, 255);
- // color the figures
- for (int k = 0; k <= label; k++) {
- color = Vec3b(d(gen), d(gen), d(gen));
- for (int i = 0; i < labels.rows; i++) {
- for (int j = 0; j < labels.cols; j++) {
- if (labels.at<uchar>(i, j) == k) {
- if (k == 0) {
- dst.at<Vec3b>(i, j) == Vec3b(255, 255, 255);
- }
- else {
- dst.at<Vec3b>(i, j) = color;
- }
- }
- }
- }
- }
- imshow("labels", dst);
- waitKey();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement