|
| 1 | +import os |
| 2 | +import cv2 |
| 3 | +import numpy as np |
| 4 | +import matplotlib.pyplot as plt |
| 5 | + |
| 6 | + |
| 7 | +class ConvolutionFilter(): |
| 8 | + |
| 9 | + def __init__(self, image): |
| 10 | + self.image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) |
| 11 | + |
| 12 | + self.sharpen = np.array(([0, -1, 0], |
| 13 | + [-1, 5, -1], |
| 14 | + [0, -1, 0])) |
| 15 | + |
| 16 | + self.sobelX = np.array([[-1, 0, 1], |
| 17 | + [-2, 0, 2], |
| 18 | + [-1, 0, 1]]) |
| 19 | + |
| 20 | + self.sobelY = np.array(([-1, -2, -1], |
| 21 | + [0, 0, 0], |
| 22 | + [1, 2, 1])) |
| 23 | + |
| 24 | + self.laplacian = np.array(([0, 1, 0], |
| 25 | + [1, -4, 1], |
| 26 | + [0, 1, 0])) |
| 27 | + |
| 28 | + def __convolution(self, image_roi, kernel): |
| 29 | + kernel_dimension = len(kernel) |
| 30 | + pixel_sum = 0 |
| 31 | + |
| 32 | + for i in range(kernel_dimension): |
| 33 | + for j in range(kernel_dimension): |
| 34 | + pixel_kernel_value = image_roi[i, j]*kernel[i, j] |
| 35 | + pixel_sum = pixel_sum+pixel_kernel_value |
| 36 | + |
| 37 | + if pixel_sum < 0: |
| 38 | + return 0 |
| 39 | + else: |
| 40 | + return pixel_sum % 255 |
| 41 | + |
| 42 | + def __applyFilter(self, kernel): |
| 43 | + image = self.image |
| 44 | + filtered_image = np.zeros(image.shape) |
| 45 | + |
| 46 | + for row in range(1, len(image)-1): |
| 47 | + for col in range(1, len(image[row])-1): |
| 48 | + |
| 49 | + pixels = image[row-1:row+2, col-1:col+2] |
| 50 | + pixel_kernel = (pixels * kernel).sum() |
| 51 | + if pixel_kernel > 0: |
| 52 | + filtered_image[row, col] = pixel_kernel % 255 |
| 53 | + else: |
| 54 | + filtered_image[row, col] = 0 |
| 55 | + |
| 56 | + return filtered_image |
| 57 | + |
| 58 | + def applySharpen(self): |
| 59 | + kernel = self.sharpen |
| 60 | + |
| 61 | + filtered_image = self.__applyFilter(kernel) |
| 62 | + return filtered_image |
| 63 | + |
| 64 | + def applySobelX(self): |
| 65 | + kernel = self.sobelX |
| 66 | + |
| 67 | + filtered_image = self.__applyFilter(kernel) |
| 68 | + return filtered_image |
| 69 | + |
| 70 | + def applySobelY(self): |
| 71 | + kernel = self.sobelY |
| 72 | + |
| 73 | + filtered_image = self.__applyFilter(kernel) |
| 74 | + return filtered_image |
| 75 | + |
| 76 | + def applyLaplacian(self): |
| 77 | + kernel = self.laplacian |
| 78 | + |
| 79 | + filtered_image = self.__applyFilter(kernel) |
| 80 | + return filtered_image |
| 81 | + |
| 82 | + def applyCannyEdge(self): |
| 83 | + |
| 84 | + filtered_image = cv2.Canny(self.image, 50, 240) |
| 85 | + return filtered_image |
0 commit comments