<jupyter_start><jupyter_text>Practical work 4: Frequency filtering, color<jupyter_code>import numpy as np
from numpy.fft import fft2,ifft2,fftshift
import matplotlib.pyplot as plt
from PIL import Image

def imshow(I,title=None,size=500):
    """ display an image with a specific size """
    plt.figure(figsize=(size//80,size//80))
    plt.gray()
    plt.imshow(I)
    if title: plt.title(title)
    plt.show()<jupyter_output><empty_output><jupyter_text>Exercice 1 - Frequency filtering1. Compute than display the centered module of Fourier transform of `img/mandrill.png` (use functions seen in previous lessons).<jupyter_code>def computeFT(I):
    """ Array -> Array[complex] """
    return fft2(I)

def computeFTI(I):
    """ Array -> Array[complex] """
    return ifft2(I)

def toVisualizeFT(If):
    """ Array[complex] -> Array[float] """
    return fftshift(If)

def toVisualizeLogFT(If):
    """ Array[complex] -> Array[float] """
    return np.log(fftshift(If))
def thresholdImage(I,s):
    return np.where((I<s),0,255)
    """ Array*int -> Array """
threshold=1e-10

mandrill = np.array(Image.open('img/mandrill.png'))
ft_mandrill = computeFT(mandrill)
ft_mandrill = toVisualizeFT(ft_mandrill)
imshow(thresholdImage(ft_mandrill, threshold))<jupyter_output><empty_output><jupyter_text>2. Write a function `idealLowPassFilter(n,m,fc)` returning an ideal low pass filter with frequency cutoff $f_c$ and size $n\times m$. Recall: this function set to 1 pixels at Euclidian distance $f_c$ from the center (null frequency).<jupyter_code>def idealLowPassFilter(n,m,fc):
    res=np.zeros([n,m])
    center=np.array((int(n/2),int(m/2)))
    for i in range(len(res)):
        for j in range(len(res[i])):
            vc=np.array((i+1,j+1))
            if(np.linalg.norm(center - vc)<fc):
                res[i][j]=1
    return res
    

def idealLowPassFilter2(n,m,fc):
    x=np.arange(n)-n/2
    y=np.arange(m)-m/2
    X,Y=np.meshgrid(y,x)
    return np.where(X**2+Y**2>(fc**2),0,1)
imshow(idealLowPassFilter2(25,25,10))<jupyter_output><empty_output><jupyter_text>3. Write a function `lowPass(I,fc)` performing a low pass filtering of an image $I$. The function should - compute the centered Fourier transform of $I$ - multiply point-by-point the spectrum with the ideal low filter produced by `idealLowPassFilter()` - uncenter the filtered spectrum and apply the inverse Fourier transform (use function `ifft2()` from module `numpy.fft`) - return the real part of filtered image<jupyter_code>def lowPass(I,fc):
    n,m=I.shape
    res=computeFT(I)
    res_tv= np.fft.fftshift(res)
    resf=res_tv*idealLowPassFilter2(n,m,fc)
    resf2=np.fft.ifft2(resf)
    return np.abs(resf2)<jupyter_output><empty_output><jupyter_text>4. Experiment this function on `img/mandrill.png` and `img/lena.jpg` with various values of cut off $f_c$. - give two effects that appears when $f_c$ decreases, - propose two applications of this filtering.<jupyter_code>mandrill2=lowPass(mandrill,20)
res=computeFT(mandrill2)
res_tv= np.fft.fftshift(res)
imshow(thresholdImage(res_tv, threshold))
imshow(mandrill2)
lena = np.array(Image.open('img/lena.jpg'))

lena2=lowPass(lena,5)
res=computeFT(lena2)
res_tv= np.fft.fftshift(res)
imshow(thresholdImage(res_tv, threshold))
imshow(lena2)<jupyter_output><empty_output><jupyter_text>Exercice 2 -  Linear filtering (convolution)1. Given a kernel convolution of size $d\times d$, $d$ being odd. How many lines and columns should be added to each side of the image to apply this filter? The image is supposed surrounded by zero values. 2. Write a function `imagePad(I,h)` getting an image and a kernel, returning a new image padded with zeros according to question 1. It is not allowed to use a module implementing the padding.<jupyter_code>def Imagepad(I,h):
    f=h.shape[0]
    m,c= I.shape
    res=np.zeros((m+f,c+f))
    b=int(f/2)-1
    print(b)
    for i in range(m+f-1):
        for j in range(c+f-1):
            if i<b or i>m+b-1 or j>c+b-1 or j<b:
                res[i][j]=0
            else:
                res[i][j]=I[i-b][j-b]
    return res
g=np.zeros((100,100))

lenaa=Imagepad(lena,g) 

imshow(lenaa)<jupyter_output>49<jupyter_text>3. Write a function `conv2(I,h)` getting an image and a kernel and returning the convolution of $I$ by $h$. The function should return an image having the same shape than $I$. It is not allowed to use a module implementing the convolution.<jupyter_code>def conv2(I,h):
    a,c=I.shape
    lenh=h.shape[0]
    f=int(lenh/2-1)
    res=Imagepad(I,h)
    for i in range(f,a+f):
        for j in range(f,f+c):
            for i in range(h.shape[0]):
               
    return res
def conv2(I,h):
    Impad=Imagepad(I,h)
    output = np.zeros_like(Impad)
    for x in range(I.shape[1]):
        for y in range(I.shape[0]):
            
            output[y, x] = (h * Impad[y: y+h.shape[0], x: x+h.shape[0]]).sum()

    return output<jupyter_output><empty_output><jupyter_text>4. Try this function on mean filter of size $3\times3$, $5\times 5$ and $7\times 7$. Discuss the results.<jupyter_code>h=np.ones((11,11))
lenaa=conv2(lena,h)
imshow(lenaa)<jupyter_output>4<jupyter_text>5. Display the transfert function of these mean filters. For a better visualization, use the zero-padding technique to obtain a filter with a large size (for instance $256\times 256$). Use `imshow()` and `toVisualizeLogFT()`. 6. Interpretation: what is the analytic expression of the transfert function of a mean filter? Is  it an ideal low pass filter? 7. Bonus question: perform the same study for the Gaussian kernel. Determine $\sigma$ in order to have filter of size $3\times3$, $5\times5$, and $7\times7$.<jupyter_code>def gaussianKernel(sigma):
    """ double -> Array
        return a gaussian kernel of standard deviation sigma
    """
    n2 = np.int(np.ceil(3*sigma))
    x,y = np.meshgrid(np.arange(-n2,n2+1),np.arange(-n2,n2+1))
    kern = np.exp(-(x**2+y**2)/(2*sigma*sigma))
    return  kern/kern.sum()
### your answer start below<jupyter_output><empty_output><jupyter_text>Exercice 3: anti aliasing filtering1. Give a code that subsamples of factor 2 (use function `subSample2()` given in TME3) the image `img/barbara.png`. 2. Give a code that subsamples of factor 2 (use function `subSample2()`) the image `img/barbara.png` after applying an low pass filter (use `antiAliasingFilter()`). As comment, recall the principle of filtering in the frequency domain.<jupyter_code>def antiAliasingFilter(n,m):
    """ int*int -> Array """
    n2, m2 = n//2, m//2
    rn, rm = n//4, m//4
    A = np.zeros((n, m))
    A[rn:rn+n2, rm:rm+m2] = 1
    return A
### your answer start below<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1340237130421732, 'fraction_numerical': 0.022062134173795586, 'mean_word_length': 4.090909090909091, 'pattern_counts': {'":': 0, '<': 43, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '646842', 'license': 'MIT', 'n_tokens_mistral': 2476, 'n_tokens_neox': 2367, 'n_words': 649, 'path': 'S1/BIMA/TME/TME4/.ipynb_checkpoints/TME4DurandKordon-checkpoint.ipynb', 'repo_name': 'hanzopgp/MasterBioInformaticsPTs', 'size': '6663'}