Advertisement
Guest User

Untitled

a guest
Dec 16th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. unsigned long components(int *gimage) {
  2.     int width = image.width();
  3.     int height = image.height();
  4.     int curComp = 0;
  5.     int compNum = 0;
  6.     int leftComp, upComp;
  7.     std::map<int, int> comps;
  8.     for (int i = 0; i < height; i++) {
  9.         for (int j = 0; j < width; j++) {
  10.             int pos = i * width + j;
  11.             if (gimage[pos] == 1) {
  12.                 if (j - 1 >= 0) {
  13.                     leftComp = gimage[i * image.width() + (j - 1)];
  14.                 }
  15.                 if (i - 1 >= 0) {
  16.                     upComp = gimage[(i - 1) * image.width() + j];
  17.                 }
  18.                 if (leftComp == 0 && upComp == 0) {
  19.                     ++curComp;
  20.                     ++compNum;
  21.                     comps[curComp] = curComp;
  22.                     gimage[pos] = curComp;
  23.                 } else {
  24.                     if (leftComp == 0) {
  25.                         gimage[pos] = comps[upComp];
  26.                     } else if (upComp == 0 || comps[leftComp] == comps[upComp]) {
  27.                         gimage[pos] = comps[leftComp];
  28.                     }
  29.                     else {
  30.                         if (leftComp < upComp) {
  31.                             gimage[pos] = comps[leftComp];
  32.                             if (comps[upComp] != comps[leftComp]) {
  33.                                 comps[upComp] = comps[leftComp];
  34.                             }
  35.                         } else {
  36.                             gimage[pos] = comps[upComp];
  37.                             if (comps[leftComp] != comps[upComp]) {
  38.                                 comps[leftComp] = comps[upComp];
  39.                             }
  40.                         }
  41.                     }
  42.                 }
  43.             }
  44.         }
  45.     }
  46.     std::set<int> difComps;
  47.     for (int i = 0; i < height; i++) {
  48.         for (int j = 0; j < width; j++) {
  49.             int pos = i * width + j;
  50.             if (gimage[pos] != 0) {
  51.                 gimage[pos] = comps[gimage[pos]];
  52.                 difComps.insert(gimage[pos]);
  53.             }
  54.         }
  55.     }
  56.  
  57.     return difComps.size();
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement