Examples of smaller Java programs that do various interesting things.

FilterExample.java 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Mike Scott
  2. // 2d array manipulation examples
  3. //import
  4. import java.awt.Color;
  5. public class FilterExample
  6. {
  7. /*
  8. *pre: image != null, image.length > 1, image[0].length > 1
  9. * image is a rectangular matrix, neighberhoodSize > 0
  10. *post: return a smoothed version of image
  11. */
  12. public Color[][] smooth(Color[][] image, int neighberhoodSize)
  13. { //check precondition
  14. assert image != null && image.length > 1 && image[0].length > 1
  15. && ( neighberhoodSize > 0 ) && rectangularMatrix( image )
  16. : "Violation of precondition: smooth";
  17. Color[][] result = new Color[image.length][image[0].length];
  18. for(int row = 0; row < image.length; row++)
  19. { for(int col = 0; col < image[0].length; col++)
  20. { result[row][col] = aveOfNeighbors(image, row, col, neighberhoodSize);
  21. }
  22. }
  23. return result;
  24. }
  25. // helper method that determines the average color of a neighberhood
  26. // around a particular cell.
  27. private Color aveOfNeighbors(Color[][] image, int row, int col, int neighberhoodSize)
  28. { int numNeighbors = 0;
  29. int red = 0;
  30. int green = 0;
  31. int blue = 0;
  32. for(int r = row - neighberhoodSize; r <= row + neighberhoodSize; r++)
  33. { for(int c = col - neighberhoodSize; c <= col + neighberhoodSize; c++)
  34. { if( inBounds( image, r, c ) )
  35. { numNeighbors++;
  36. red += image[r][c].getRed();
  37. green += image[r][c].getGreen();
  38. blue += image[r][c].getBlue();
  39. }
  40. }
  41. }
  42. assert numNeighbors > 0;
  43. return new Color( red / numNeighbors, green / numNeighbors, blue / numNeighbors );
  44. }
  45. //helper method to determine if given coordinates are in bounds
  46. private boolean inBounds(Color[][] image, int row, int col)
  47. { return (row >= 0) && (row <= image.length) && (col >= 0)
  48. && (col < image[0].length);
  49. }
  50. //private method to ensure mat is rectangular
  51. private boolean rectangularMatrix( Color[][] mat )
  52. { boolean isRectangular = true;
  53. int row = 1;
  54. final int COLUMNS = mat[0].length;
  55. while( isRectangular && row < mat.length )
  56. { isRectangular = ( mat[row].length == COLUMNS );
  57. row++;
  58. }
  59. return isRectangular;
  60. }
  61. }