package yi.iu.processor.morph;

public class Boundary {
  /**
   * Return boundary inside the target region.
   * @param b
   * @param w
   * @param h
   * @param foreground foreground color
   * @return
   */
  public static int[] getBoundary(int[] b, int w, int h, int foreground) {
    int[] boundary = new int[h*w];
    int background= 1-foreground;
    for (int i=0;i<h;i++) {
      for (int j=0;j<w;j++) {
        if (b[i*w+j]!=foreground) {
          boundary[i*w+j]= background;
          continue;
        }
        if (i-1>0 && b[(i-1)*w+j] ==background) boundary[i*w+j]=foreground;
        else if (i+1<h && b[(i+1)*w+j] ==background) boundary[i*w+j]=foreground;
        else if (j-1>0 && b[i*w+j-1] ==background) boundary[i*w+j]=foreground;
        else if (j+1<w && b[i*w+j+1] ==background) boundary[i*w+j]=foreground;
        else if (i-1>0 && j-1>0 && b[(i-1)*w+j-1] ==background) boundary[i*w+j]=foreground;
        else if (i-1>0 && j+1<w && b[(i-1)*w+j+1] ==background) boundary[i*w+j]=foreground;
        else if (i+1<h && j-1>0 && b[(i+1)*w+j-1] ==background) boundary[i*w+j]=foreground;
        else if (i+1<h && j+1<w && b[(i+1)*w+j+1] ==background) boundary[i*w+j]=foreground;
        else boundary[i*w+j]= background;
      }
    }
    return boundary;
  }
}