|
| 1 | +# @Author : ojas-wani |
| 2 | +# @File : laplacian_filter.py |
| 3 | +# @Date : 10/04/2023 |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +from cv2 import ( |
| 7 | + BORDER_DEFAULT, |
| 8 | + COLOR_BGR2GRAY, |
| 9 | + CV_64F, |
| 10 | + cvtColor, |
| 11 | + filter2D, |
| 12 | + imread, |
| 13 | + imshow, |
| 14 | + waitKey, |
| 15 | +) |
| 16 | + |
| 17 | +from digital_image_processing.filters.gaussian_filter import gaussian_filter |
| 18 | + |
| 19 | + |
| 20 | +def my_laplacian(src: np.ndarray, ksize: int) -> np.ndarray: |
| 21 | + """ |
| 22 | + :param src: the source image, which should be a grayscale or color image. |
| 23 | + :param ksize: the size of the kernel used to compute the Laplacian filter, |
| 24 | + which can be 1, 3, 5, or 7. |
| 25 | +
|
| 26 | + >>> my_laplacian(src=np.array([]), ksize=0) |
| 27 | + Traceback (most recent call last): |
| 28 | + ... |
| 29 | + ValueError: ksize must be in (1, 3, 5, 7) |
| 30 | + """ |
| 31 | + kernels = { |
| 32 | + 1: np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]), |
| 33 | + 3: np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]), |
| 34 | + 5: np.array( |
| 35 | + [ |
| 36 | + [0, 0, -1, 0, 0], |
| 37 | + [0, -1, -2, -1, 0], |
| 38 | + [-1, -2, 16, -2, -1], |
| 39 | + [0, -1, -2, -1, 0], |
| 40 | + [0, 0, -1, 0, 0], |
| 41 | + ] |
| 42 | + ), |
| 43 | + 7: np.array( |
| 44 | + [ |
| 45 | + [0, 0, 0, -1, 0, 0, 0], |
| 46 | + [0, 0, -2, -3, -2, 0, 0], |
| 47 | + [0, -2, -7, -10, -7, -2, 0], |
| 48 | + [-1, -3, -10, 68, -10, -3, -1], |
| 49 | + [0, -2, -7, -10, -7, -2, 0], |
| 50 | + [0, 0, -2, -3, -2, 0, 0], |
| 51 | + [0, 0, 0, -1, 0, 0, 0], |
| 52 | + ] |
| 53 | + ), |
| 54 | + } |
| 55 | + if ksize not in kernels: |
| 56 | + msg = f"ksize must be in {tuple(kernels)}" |
| 57 | + raise ValueError(msg) |
| 58 | + |
| 59 | + # Apply the Laplacian kernel using convolution |
| 60 | + return filter2D( |
| 61 | + src, CV_64F, kernels[ksize], 0, borderType=BORDER_DEFAULT, anchor=(0, 0) |
| 62 | + ) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + # read original image |
| 67 | + img = imread(r"../image_data/lena.jpg") |
| 68 | + |
| 69 | + # turn image in gray scale value |
| 70 | + gray = cvtColor(img, COLOR_BGR2GRAY) |
| 71 | + |
| 72 | + # Applying gaussian filter |
| 73 | + blur_image = gaussian_filter(gray, 3, sigma=1) |
| 74 | + |
| 75 | + # Apply multiple Kernel to detect edges |
| 76 | + laplacian_image = my_laplacian(ksize=3, src=blur_image) |
| 77 | + |
| 78 | + imshow("Original image", img) |
| 79 | + imshow("Detected edges using laplacian filter", laplacian_image) |
| 80 | + |
| 81 | + waitKey(0) |
0 commit comments