Slmaan

Task 1: Image Convolution

Apr 18th, 2023 (edited)
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.61 KB | None | 0 0
  1. """
  2.    |NAME : Slmaan AL-Beady
  3.    |DR   : Jafar  Abu-Khait
  4.    |0112551 Computer Vision Spring 2023  
  5.    |Programming Assignment # 1
  6. """
  7. import numpy as np
  8. import cv2 as cv
  9. from matplotlib import pyplot as plt
  10.  
  11.  
  12. def convolution(image, filter_type, threshold):
  13.     """
  14.    Define kernel based on filter type and apply convolution
  15.    Parameters:
  16.    img (numpy.ndarray): The image to apply the filter to.
  17.    filter (str): The type of filter to apply. Currently supports "gaussian" and "prewitt".
  18.    x (int): -/ Threshold value for the filter prewitt    \-
  19. .           -/    sigma   value for the filter Gaussian   \-
  20.  
  21.    Returns:
  22.    numpy.ndarray: The filtered image.
  23.    """
  24.     kernel = None
  25.     if filter_type == "gaussian":
  26.         kernel = generate_gaussian_kernel(threshold) #threshold=sigma
  27.         output = cv.filter2D(image, -1, kernel)
  28.     elif filter_type == "prewitt":
  29.         kernel_x = np.array([[-1,0,1],[-1,0,1],[-1,0,1]])
  30.         kernel_y = np.array([[-1,-1,-1],[0,0,0],[1,1,1]])
  31.         # Apply Gaussian blur to image before applying Prewitt filter
  32.         image = cv.GaussianBlur(image, (11, 11), 0)
  33.         grad_x = cv.filter2D(image, -1, kernel_x)
  34.         grad_y = cv.filter2D(image, -1, kernel_y)
  35.         # Calculate gradient magnitution and threshold the result
  36.         magnitution = np.sqrt(grad_x ** 2 + grad_y ** 2)
  37.         output = np.zeros_like(magnitution, dtype=np.uint8)
  38.         output[magnitution > threshold] = 255
  39.     else:
  40.         raise Exception("Invalid filter type: %s. Supported types are 'gaussian' and 'prewitt'." % filter_type)
  41.     return output
  42.  
  43.  
  44. def generate_gaussian_kernel(sigma):
  45.     """
  46.        Generates a Gaussian kernel based on sigma.
  47.  
  48.        Parameters:
  49.        sigma (int): The sigma value to use.
  50.  
  51.        Returns:
  52.        numpy.ndarray: The Gaussian kernel.
  53.    """    
  54.     kernel = np.zeros((2 * sigma + 1, 2 * sigma + 1), dtype=np.float32)
  55.     summation = 0.0
  56.     for x in range(-sigma, sigma + 1):
  57.         for y in range(-sigma, sigma + 1):
  58.             kernel[x + sigma, y + sigma] = np.exp(-(x **2 + y **2) /(2 * sigma ** 2)) / np.sqrt(np.pi * (2 * sigma ** 2))
  59.             summation += kernel[x + sigma, y + sigma]
  60.     # Normalize kernel so that all elements sum to 1
  61.     kernel /= summation
  62.     return kernel
  63.  
  64.  
  65. def plot_results(images, titles):
  66.     # Plot images and titles in a grid
  67.     num_images = len(images)
  68.     rows = int(num_images/3) + (num_images%3 > 0)
  69.     plt.figure(figsize=(20, 20))
  70.     for i, (image, title) in enumerate(zip(images, titles)):
  71.         plt.subplot(rows, 3, i+1)
  72.         plt.title(title), plt.xticks([]), plt.yticks([])
  73.         plt.imshow(image, cmap='gray')
  74.     plt.show()
  75.  
  76.  
  77. # First Part
  78. def run_first_part():
  79.     # Apply Gaussian filter to House1.jpg for different kernel sizes
  80.     image = cv.imread("House1.jpg")
  81.     images = [image]
  82.     titles = ["Original Image"]
  83.     for x in range(1, 4):
  84.         filtered = convolution(image, "gaussian", x)
  85.         images.append(filtered)
  86.         titles.append("Gaussian Filter Size %s" % (2*x+1))
  87.     plot_results(images, titles)
  88.  
  89.  
  90. # Second Part
  91. def run_second_part():
  92.     # Apply Prewitt filter to House2.jpg for different threshold values
  93.     image = cv.imread("House2.jpg")
  94.     thresholds = [1, 5, 10]
  95.     images = [image]
  96.     titles = ["Original Image"]
  97.     for threshold in thresholds:
  98.         filtered = convolution(image, "prewitt", threshold)
  99.         images.append(filtered)
  100.         titles.append("Prewitt Filter Threshold %s" % threshold)
  101.     plot_results(images, titles)
  102.  
  103.  
  104. if __name__ == "__main__":
  105.     run_first_part()
  106.     run_second_part()
  107.  
Advertisement
Add Comment
Please, Sign In to add comment