Search code examples
javaalgorithmimage-processingprocessingedge-detection

Edge Detection Algorithm with Processing (Java)


i want to code an algorithm, that can do an edge detection for an image. I already have a part of the code, which detects all edges in horizontal way. Example picture:enter image description here

But i need an edge detection in horizontal, vertical and diagonal way. If i try it the same way like the horizontal way, i get an ArrayOutOfBoundaryException (e.g. if i do pixRechts= color(meinBild1.pixels[index1(x+1,y)]); )

Do u have any ideas how to do that? Im using Processing.

Thanks.

My Code until now.

PImage meinBild1, meinBild2;
int anzahlPixel1, anzahlPixel2;

void setup()
{
  size(1000,250); 


  meinBild1 = loadImage("stonehenge.jpg"); //500x250
  meinBild2 = createImage(500,250, RGB);


  anzahlPixel1 = meinBild1.width * meinBild1.height;
  anzahlPixel2 = meinBild2.width * meinBild2.height;


  meinBild1.loadPixels();
  meinBild2.loadPixels();

  edgeDetection();


  meinBild1.updatePixels();
  image(meinBild1, 0, 0);  


  meinBild2.updatePixels();
  image(meinBild2, 500, 0);  

}

void draw()
{

}

void edgeDetection()
{
  int x,y;
  float edge;
  color pix, pixLinks;


  for ( x = 1; x < meinBild2.width; x++) 
  { 
    for ( y = 0; y < meinBild2.height; y++) 
    {

      pix= color(meinBild1.pixels[index1(x,y)]);
      pixLinks= color(meinBild1.pixels[index1(x-1,y)]);

      edge = abs(brightness(pix)-brightness(pixLinks));

      if (edge>50) {
        edge=255;
      }
      else{
          edge=0;
      }

      meinBild2.pixels[index2(x,y)] = color(edge);

    }
  }

}

int index1(int x, int y)
{
  int r= x + y*meinBild1.width;
  return r;
} 


int index2(int x, int y)
{
  int r= x + y*meinBild2.width;
  return r;
} 

Solution

  • (e.g. if i do pixRechts= color(meinBild1.pixels[index1(x+1,y)]); )

    This line would just find the already detected edges.

    I would recommend you to do it like you mentioned by your example, but you should just detect for:

    1. x -1, y -1 for vertical
    2. x -1, y +1 for vertical
    3. x, y -1 for horizontal

    You should also look at your two loops. The above mentioned cases will also run in an ArrayOutOfBoundsException with your code.

    1. will stop at the first pixel
    2. will stop at the last y pixel