Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. void Bfs() {
  2.  
  3. Mat src, dst, labels;
  4. src = imread("Images/shapes.bmp", CV_LOAD_IMAGE_GRAYSCALE);
  5. labels = Mat::zeros(src.rows, src.cols, CV_8UC1);
  6. dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
  7. int label = 0;
  8.  
  9. for (int i = 0; i < src.rows; i++)
  10. for (int j = 0; j < src.cols; j++)
  11. if (src.at<uchar>(i, j) == 0 && labels.at<uchar>(i, j) == 0)
  12. {
  13. label++;
  14. std::queue<Point2i> Q;
  15. labels.at<uchar>(i, j) = label;
  16. Q.push(Point2i(j, i));
  17. while (!Q.empty())
  18. {
  19. Point2i qu = Q.front();
  20. Q.pop();
  21. int di[8] = { -1, -1, -1, 0, 0, 1, 1, 1 };
  22. int dj[8] = { -1, 0, 1, -1, 1, -1, 0, 1 };
  23. for (int k = 0; k < 8; k++)
  24. {
  25. int w = qu.y + di[k];
  26. int h = qu.x + dj[k];
  27. if (src.at<uchar>(w, h) == 0 && labels.at<uchar>(w, h) == 0)
  28. {
  29. labels.at<uchar>(w, h) = label;
  30. Q.push(Point2i(h, w));
  31. }
  32. }
  33. }
  34. }
  35.  
  36. Vec3b colors;
  37.  
  38. for (int i = 0; i <= label; i++)
  39. {
  40.  
  41. colors = Vec3b(rand() % 256, rand() % 256, rand() % 256);
  42.  
  43. for (int j = 0; j < src.rows; j++)
  44. for (int k = 0; k < src.cols; k++)
  45. if (labels.at<uchar>(j, k) == i)
  46. if (i == 0)
  47. {
  48. dst.at<Vec3b>(j, k) = Vec3b(255, 255, 255);
  49. }
  50. else
  51. {
  52. dst.at<Vec3b>(j, k) = colors;
  53. }
  54. }
  55. imshow("Initial", src);
  56. imshow("Final", dst);
  57. waitKey(0);
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement