Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. void labelling(Mat img)
  2. {
  3.     int label = 0;
  4.  
  5.     Scalar colorLUT[1000] = { 0 };
  6.     Scalar color;
  7.     for (int i = 1; i < 1000; i++)
  8.     {
  9.         Scalar color(rand() & 255, rand() & 255, rand() & 255);
  10.         colorLUT[i] = color;
  11.     }
  12.     colorLUT[0] = Scalar(255, 255, 255); // fundalul va fi alb
  13.  
  14.     Mat labels = Mat::zeros(img.size(), CV_16SC1);
  15.     Mat dst = Mat::zeros(img.size(), CV_8UC3);
  16.  
  17.     for (int i = 0; i < img.rows; i++)
  18.         for (int j = 0; j < img.cols; j++)
  19.         {
  20.             if (img.at<uchar>(i, j) == 0 && labels.at<short>(i,j) == 0)
  21.             {
  22.                 label++;
  23.                 std::queue <Point> que;
  24.                 labels.at<short>(i,j)  = label;
  25.                 que.push({ i,j });
  26.                 while(!que.empty())
  27.                 {
  28.                     Point oldest = que.front();
  29.                     uchar neighbors[8];
  30.                     int di[8] = { -1,-1,-1,0,0,1,1 ,1 };
  31.                     int dj[8] = { -1,0,1,-1, 1,-1,0,1};
  32.                     int x = oldest.x;
  33.                     int y = oldest.y;
  34.                     for (int k = 0; k < 8; k++)
  35.                     {
  36.                         int vecin_i = x + di[k];
  37.                         int vecin_j = y + dj[k];
  38.                         if(vecin_i>=0 && vecin_j>=0 && vecin_i<img.rows && vecin_j <img.cols)
  39.                             if (img.at<uchar>(vecin_i,vecin_j) == 0 && labels.at<short>(vecin_i,vecin_j) == 0)
  40.                             {
  41.                                 labels.at<short>(vecin_i,vecin_j) = label;
  42.                                 que.push(Point(vecin_i,vecin_j));
  43.                             }
  44.                     }
  45.                     que.pop();
  46.  
  47.                 }
  48.             }
  49.         }
  50.  
  51.     for (int i = 1; i < labels.rows - 1; i++)
  52.         for (int j = 1; j < labels.cols - 1; j++)
  53.         {
  54.             Scalar color = colorLUT[labels.at<short>(i, j)]; // valabil pt. Met. 1 BFS
  55.             dst.at<Vec3b>(i, j)[0] = color[0];
  56.             dst.at<Vec3b>(i, j)[1] = color[1];
  57.             dst.at<Vec3b>(i, j)[2] = color[2];
  58.         }
  59.  
  60.     imshow("labelled", dst);
  61.     waitKey();
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement