# Fast Biased Convolution Algorithm

a guest
Feb 18th, 2015
441
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1.
2. public void blur(int[] pixels, int width, int height) {
3. int[][] matrix = new int[][]{
4. {1, 1, 1},
5. {1, 1, 1},
6. {1, 1, 1}
7. };
8. int parts = 9;
9. convolve(pixels, 0, width, 15, 30, 5, 5, matrix, parts);
10. }
11.
12. public void emboss(int[] pixels, int width, int height) {
13. int[][] matrix = new int[][]{
14. {2, 0, 0},
15. {0, -1, 0},
16. {0, 0, -1}
17. };
18. int parts = 1;
19. convolve(pixels, 0, width, 0, 0, width - 2, height - 2, matrix, parts);
20. }
21.
22.
23. public static void convolve(int[] pixels, int offset, int stride, int x, int y, int width, int height, int[][] matrix, int parts) {
24. int startIndex = x + (y * stride);
25. int lastIndex = (x + width-1) + ((y + height-1) * stride);
26. int x_pos = x;
27. int y_pos = y;
28. int indexInc = 1;
29. int yinc = 0;
30. int xinc = 1;
31.
32. for (int i = 0, s = width + height; i < s; i++) {
33. if (i==width) {
34. indexInc=stride;
35. yinc = 1;
36. xinc = 0;
37. }
38. int x_counter = x_pos;
39. int index = startIndex;
40. while (x_counter >= x && index <= lastIndex) {
41. pixels[offset + index] = convolve(pixels, stride, offset + index, matrix, parts);
42. x_counter--;
43. index += stride - 1;
44. }
45. startIndex += indexInc;
46. x_pos += xinc;
47. y_pos += yinc;
48. }
49. }
50.
51.
52. private static int crimp(int color) {
53. return (color >= 0xFF) ? 0xFF : (color < 0) ? 0 : color;
54. }
55.
56. private static int convolve(int[] pixels, int stride, int index, int[][] matrix, int parts) {
57. int redSum = 0;
58. int greenSum = 0;
59. int blueSum = 0;
60. int pixel, factor;
61. for (int j = 0, m = matrix.length; j < m; j++, index++) {
62. for (int k = 0, n = matrix[j].length, q = index; k < n; k++, q += stride) {
63. pixel = pixels[q];
64. factor = matrix[j][k];
65. redSum += factor * ((pixel >> 16) & 0xFF);
66. greenSum += factor * ((pixel >> 8) & 0xFF);
67. blueSum += factor * ((pixel) & 0xFF);
68. }
69. }
70. return 0xFF000000 | ((crimp(redSum / parts) << 16) | (crimp(greenSum / parts) << 8) | (crimp(blueSum / parts)));
71. }