Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Bfs() {
- Mat src, dst, labels;
- src = imread("Images/shapes.bmp", CV_LOAD_IMAGE_GRAYSCALE);
- labels = Mat::zeros(src.rows, src.cols, CV_8UC1);
- dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
- int label = 0;
- for (int i = 0; i < src.rows; i++)
- for (int j = 0; j < src.cols; 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 qu = Q.front();
- Q.pop();
- int di[8] = { -1, -1, -1, 0, 0, 1, 1, 1 };
- int dj[8] = { -1, 0, 1, -1, 1, -1, 0, 1 };
- for (int k = 0; k < 8; k++)
- {
- int w = qu.y + di[k];
- int h = qu.x + dj[k];
- if (src.at<uchar>(w, h) == 0 && labels.at<uchar>(w, h) == 0)
- {
- labels.at<uchar>(w, h) = label;
- Q.push(Point2i(h, w));
- }
- }
- }
- }
- Vec3b colors;
- for (int i = 0; i <= label; i++)
- {
- colors = Vec3b(rand() % 256, rand() % 256, rand() % 256);
- for (int j = 0; j < src.rows; j++)
- for (int k = 0; k < src.cols; k++)
- if (labels.at<uchar>(j, k) == i)
- if (i == 0)
- {
- dst.at<Vec3b>(j, k) = Vec3b(255, 255, 255);
- }
- else
- {
- dst.at<Vec3b>(j, k) = colors;
- }
- }
- imshow("Initial", src);
- imshow("Final", dst);
- waitKey(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement