convolution.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. Convolution functions to apply on images
  3. """
  4. # main imports
  5. import numpy as np
  6. def convolution2D(image, kernel, kernel_size=(5, 5), stride=1):
  7. """Apply 2D convolution on image using specific kernel from `ipfml.filters.kernels`
  8. Args:
  9. image: 2D image to apply convolution on
  10. kernel: specific kernel from `ipfml.filters.kernels` to use
  11. kernel_size: window size to use (default (5, 5))
  12. Returns:
  13. 2D numpy array obtained from image using kernel
  14. Example:
  15. >>> from ipfml.filters.convolution import convolution2D
  16. >>> from ipfml.filters.kernels import plane_mean
  17. >>> import numpy as np
  18. >>> image = np.arange(81).reshape([9, 9])
  19. >>> convolved_image = convolution2D(image, plane_mean, (3, 3))
  20. >>> convolved_image.shape
  21. (7, 7)
  22. """
  23. img = np.array(image)
  24. width, height = img.shape
  25. kernel_width, kernel_height = kernel_size
  26. if kernel_width % 2 == 0 or kernel_height % 2 == 0:
  27. raise ValueError("Invalid kernel size, need to be of odd size")
  28. padding_height = (kernel_width - 1) / 2
  29. padding_width = (kernel_width - 1) / 2
  30. img_diff = []
  31. for i in range(width):
  32. if i >= padding_width and i < (
  33. width - padding_width) and i % stride == 0:
  34. row_diff = []
  35. for j in range(height):
  36. if j >= padding_height and j < (
  37. height - padding_height) and j % stride == 0:
  38. # pixel in the center of kernel window size, need to extract window from img
  39. window = img[int(i - padding_width):int(i + padding_width +
  40. 1),
  41. int(j - padding_height
  42. ):int(j + padding_height + 1)]
  43. diff = kernel(window)
  44. row_diff.append(diff)
  45. img_diff.append(row_diff)
  46. return np.array(img_diff)