Image Processing with Kernels


# -*- coding: utf-8 -*-
"""

@author: profa
"""

## Image Processing Kernels Examples....
## https://en.wikipedia.org/wiki/Kernel_(image_processing)

import numpy as np
import scipy as sp
import itertools as it
import matplotlib.pyplot as plt
from scipy import signal
#from matplotlib.animation import FuncAnimation

plt.rcParams["figure.figsize"]=(14,7)

## IMPORTANT ##
## !! YOU !! will need to change this path to upload your own image
## ----------------------------------------------------------------------

ImageLocation="C:/Users/profa/Desktop/PIX/CO PIX/AmiSam.jpg"

img = plt.imread(ImageLocation).astype(np.float)/255.
img.shape
img.shape[-1]  ## the last value - which is the num channels
plt.imshow(img)

SomeKernels={
    "Edge_Detect":np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]),
    "Identity":np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]),
    "Sharpen":np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]]) ,
    "Gaus_Blur" :np.array([[1/16, 2/16, 1/16], [2/16, 4/16, 2/16], [1/16, 2/16, 1/16]])  }


def Conv_Kernel(image, kernel):
    new_image = np.empty_like(image)
    for dim in range(image.shape[-1]): ## for all the channels
        new_image[:,:,dim] = sp.signal.convolve2d(image[:,:,dim], 
                                                  kernel,
                                                  mode="same",
                                                  boundary="symm")
    return new_image

###############################################
##Call the function on any of the following
##########################################################
#filtered_image=Conv_Kernel(img, SomeKernels["Identity"])
filtered_image=Conv_Kernel(img, SomeKernels["Edge_Detect"])
#filtered_image=Conv_Kernel(img, SomeKernels["Sharpen"])
#filtered_image=Conv_Kernel(img, SomeKernels["Gaus_Blur"])

fig, (axL, axR) = plt.subplots(ncols=2, tight_layout=True)
fig.suptitle("Edge_Detect")

axL.imshow(img)  ##on the left- the original image
axR.imshow(filtered_image) # on the right - the filtered image