Breaking

Be Strong Let's Try!

Tuesday, 17 August 2021

What Is Spatial Filtering? Different Types Of Filter In Image Processing 2021

 What is the OBJECTIVE:

The objective of this topic is to perform spatial filtering on images with different filter size.

Description of the topics:

Spatial filtering :

                         Spatial filtering is an important step of preprocessing of images. Different types of filters like smoothing filters, sharpening filters and rank filters etc. can be applied to images to achieve the desired result. 

 Averaging or smoothing filters:

                                               Averaging or smoothing filters consist of integration and they can be used for blurring or noise reduction. Blurring helps to remove small details from an image before further processing like object extraction can be performed on it. Applying a smoothing filter (or any filter for that matter) involves convolving the filter of a specific size with the entire image. The mask moves pixel by pixel while convolving with the values of the pixel intensities that it covers as shown here.
While applying a filter to an image, the boundary of the image impose a unique challenge: for the first pixel of the first row, there are no pixels behind or above it that can be multiplied with the mask value. To counter this problem, two techniques can be used:

Padding :

Adding a few rows of 0’s all around the image helps the mask to function properly. The exact number of the 0 rows that are to be added depends on the size of the mask. OR we can replace with neighboring pixel value to avoid affect of zeros on the image .

Ignoring some rows and columns: 

                                                  The first few rows and columns can be ignored and the mask can be applied to the rest of the image. The number of the rows and columns that are to be ignored depends on the size of the filter. 

There are some as usual in all the topics try them using python lets start:

1: Write generic functions for each of the following. 
2: Takes input mask size and their numeric values from the user and create the mask
3: Take image and padding size as argument and add padding on the image (either zeros or copy neighboring pixel) 
4: Take image and filter as argument and apply the filter to the image 
5: Take image as input and normalize the image between 0 - 255 Now Apply the following Masks the image and display the results .

Task 01

(1)

import cv2 as cv
import numpy as np
#(1) : Take size of mask and values of mask
def InputMask():
    rows =
int(input("Enter number of rows for mask size : "))   #take number of rows
   
cols = int(input("Enter number of columns for mask size : "))  #take number of columns
   
mask = np.zeros((rows, cols), dtype=np.uint8)        #initialize mask with zeros
   
for i in range(rows):                                #take mask values from user
       
for j in range (cols):
            mask[i][j] =
int(input("Enter mask value at location [" + str(i) + "]["+ str(j)+ "] = "))
   
return mask

(2)

#(2) : Take image and padding size and add padding to image
def Padding(image,paddingsize):
    padded_img = np.pad(image,(paddingsize,paddingsize),
'constant')     #perform zero padding
   
return padded_img

(3)

# (3) : Take image, padding siza and mask and apply averaging filter
def Filtering(img,pad_size,mask):
    dims = np.shape(mask)      
#dimensions of input mask
   
rows_mask = dims[0]    #rows of input mask
   
cols_mask = dims[1]     #columns of input mask
   
dims = np.shape(img)    #dimensions of input image
   
rows_img = dims[0]    #rows of input mask
   
cols_img = dims[1]    #columns of input mask
   
filtered_img = np.copy((rows_img, cols_img), dtype=np.uint8)  # initialize output image with zeros and same size as input image
   
factor = 1 / (rows_mask*cols_mask) #multiplication factor
   
i_end = rows_img-pad_size  #end limt of rows
   
j_end = cols_img-pad_size  #end limt of columns
   
for i in range (pad_size,i_end):
       
for j in range (pad_size,j_end):
            mask[:,:] = img[i-pad_size:i+pad_size+
1, j-pad_size:j+pad_size+1]   #mask window
           
mask = factor * mask   #multiply
           
sum = np.sum(mask)     #add all elements
           
filtered_img[i][j] = sum #add this pixel value at output image
   
return filtered_img

 

(4)

#(4) : Take image and normalizes between 0-255
def Normalization(img):
    dims = np.shape(img)
#dimensions of input image
   
rows = dims[0]   #rows of input mask
   
cols = dims[1]    #columns of input mask
   
normalized_img = np.zeros((rows,cols),dtype=np.uint8)  # initialize output image with zeros and same size as input image)
   
normalized_img = cv.normalize(img,normalized_img,0,255,cv.NORM_MINMAX) #apply normalization
   
return normalized_img
#take mask from user
mask = InputMask()   
#Perform zero padding
img = cv.imread('Te.tif’,0) #read input image
dims = np.shape(mask)                   #for determining padding size
rows = dims[0]
padding_size =
int(np.floor(rows/2))   #padding size is half the mask size rounded down
padded_img = Padding(img,padding_size) #perform padding
filtered_img = Filtering(padded_img,padding_size,mask) #applying filter on image
normalized_img = Normalization(img)                    #normalizing the image
print("Mask\n",mask)
print("Padding size : ", padding_size)
print("Original Image \n",img)
print("Padded Image \n",padded_img)
# Displaying masked and normalized images
cv.imshow('After applying filter', filtered_img)
cv.imshow(
'After applying normalization, normalized_img)
cv.waitKey(
0)

Output:
(A):



(B):

(C):
(D):
(E):

6. Explore the effect of median filtering with different neighborhood sizes for the image below. 

Code

import numpy as np
import cv2 as cv
img = cv.imread(
‘x.tif',0#read input image
n = int(input('Enter neighnourhood (mask size) : '))  #take neighbourhood size
dims = np.shape(img)    #dimensions of image
rows = dims[0] #rows of image
cols = dims[1] #columns of image
padding_size = int(np.floor(n/2)) #padding size is half the mask size rounded down
masked_img = np.zeros((rows + padding_size, cols + padding_size), dtype=np.uint8) #initialize output image with zeros
mask = np.zeros((padding_size, padding_size), dtype=np.uint8)        #initialize mask with zeros
padded_img = np.copy(masked_img)                                     #initialize padded image with zeros
padded_img = np.pad(img,(padding_size,padding_size),'constant')      #zero padding done
# Applying median filter

for i in range(padding_size, rows):
   
for j in range(padding_size,cols):
        mask=padded_img[i-padding_size:i+padding_size+
1,j-padding_size:j+padding_size+1]
        mask=np.ravel(mask)    
# Convert to sigle row
       
mask=np.sort(mask)      # Sort in ascending order
       
masked_img[i,j]=np.median(mask)  # take median
# Showing Images on Screen
cv.imshow('median',masked_img)
cv.waitKey(0)

Output:






















No comments:

Post a Comment

Pages