Facebook
From Speedy Anoa, 7 Years ago, written in Java.
Embed
Download Paste or View Raw
Hits: 272
  1. /**
  2.  * Edge Detection.
  3.  *
  4.  * Exposing areas of contrast within an image
  5.  * by processing it through a high-pass filter.
  6.  */
  7.  
  8. float[][] kernel = { { 0, 0, 0 },
  9.                      { 1,  0, -1 },
  10.                      { 0, 0, 0 } };
  11.  
  12. //size(200, 200);
  13. PImage img = loadImage("aula01.jpg"); // Load the original image
  14. int w = img.width;
  15. int h = img.height;
  16. size(2*w,h);
  17. image(img, 0, 0); // Displays the image from point (0,0)
  18. img.loadPixels();
  19. // Create an opaque image of the same size as the original
  20. PImage edgeImg = createImage(img.width, img.height, RGB);
  21. // Loop through every pixel in the image.
  22. for (int y = 1; y < img.height-1; y++) { // Skip top and bottom edges
  23.   for (int x = 1; x < img.width-1; x++) { // Skip left and right edges
  24.     float sum = 0; // Kernel sum for this pixel
  25.     for (int ky = -1; ky <= 1; ky++) {
  26.       for (int kx = -1; kx <= 1; kx++) {
  27.         // Calculate the adjacent pixel for this kernel point
  28.         int pos = (y + ky)*img.width + (x + kx);
  29.         // Image is grayscale, red/green/blue are identical
  30.         float val = red(img.pixels[pos]);
  31.         // Multiply adjacent pixels based on the kernel values
  32.         sum += kernel[ky+1][kx+1] * val;
  33.       }
  34.     }
  35.     // For this pixel in the new image, set the gray value
  36.     // based on the sum from the kernel
  37.     edgeImg.pixels[y*img.width + x] = color(sum);
  38.   }
  39. }
  40. // State that there are changes to edgeImg.pixels[]
  41. edgeImg.updatePixels();
  42. image(edgeImg, w, 0); // Draw the new image