import numpy as np
import matplotlib.pyplot as plt
# Question 2
h1 = np.zeros((512,512))
h1[246:346,150:350] = 1
plt.imshow(h1,cmap='gray',vmin=0,vmax=1)
plt.show()
# question 3
# version vue pendant le cours
def ImTranslate(h,tau):
M, N = h.shape
res = np.zeros((M,N))
res[tau[0]:M,tau[1]:N] = h[0:(M-tau[0]),0:(N-tau[1])]
res[0:tau[0],0:tau[1]] = h[(M-tau[0]):M,(N-tau[1]):N]
res[0:tau[0],tau[1]:N] = h[(M-tau[0]):M,0:(N-tau[1])]
res[tau[0]:M,0:tau[1]] = h[0:(M-tau[0]),(N-tau[1]):N]
return res
# version alternative (avec l'utilisation de l'opération modulo)
def ImTranslate(h,tau):
M, N = h.shape
res = np.zeros((M,N))
indrow = ((tau[0]+np.arange(M))%M).reshape(M,1)
indcol = ((tau[1]+np.arange(N))%N).reshape(1,N)
res[indrow,indcol] = h
return res
h1_tr = ImTranslate(h1,[250,250])
plt.imshow(h1_tr,cmap='gray',vmin=0,vmax=1)
plt.show()
# question 4
def DSN(h,n):
M, N = h.shape
res = 0
for i in range(n):
tau = np.random.randint(M), np.random.randint(N)
res += ImTranslate(h,tau)
return res
# on fait une fonction pour afficher l'image et ses DSN avec des valeurs croissantes de n:
def ShowDSN(h):
ns = [10, 100, 1000]
plt.figure(figsize=(16,8))
plt.subplot(1,len(ns)+1,1)
plt.imshow(h,cmap='gray')
plt.title('original image')
for i, n in enumerate(ns):
h_DSN = DSN(h,n)
plt.subplot(1,len(ns)+1,i+2)
plt.imshow(h_DSN,cmap='gray')
plt.title('DSN, n='+str(n))
plt.show()
ShowDSN(h1)
h2 = plt.imread('images/coeur.bmp')
h2 = np.mean(h2,2)
ShowDSN(h2)
h3 = plt.imread('images/briques.bmp')
h3 = np.mean(h3,2)
ShowDSN(h3)
h4 = plt.imread('images/mer.bmp')
h4 = np.mean(h4,2)
ShowDSN(h4)
# question 5
def GaussImage(N,b=20):
if isinstance(b,int) or isinstance(b,float):
b *= np.array([-1,1,-1,1])
h = np.exp(-(np.ones((N,1))*np.linspace(b[0],b[1],N)[None,:])**2
-(np.ones((N,1))*np.linspace(b[2],b[3],N)[None,:]).T**2)
return h
def ShowDFT(h):
# DFT de l'image h
fh = np.fft.fft2(h)
# module de la DFT
afh = np.abs(fh)
# phase de la DFT
pfh = np.angle(fh)
# affichage
plt.figure(figsize=(16,8))
plt.subplot(1,3,1)
plt.imshow(h,cmap='gray')
plt.title('image')
plt.subplot(1,3,2)
plt.imshow(np.log(0.1+np.fft.fftshift(afh)),cmap="gray")
plt.title('amplitude de la DFT (centrée et échelle log)')
plt.subplot(1,3,3)
plt.imshow(np.fft.fftshift(pfh),cmap="gray")
plt.title('phase de la DFT (centrée)')
plt.show()
# l'image du rectangle
ShowDFT(h1)
# quelques images du dossier
ShowDFT(h2)
ShowDFT(h3)
ShowDFT(h4)
# image d'une gaussienne
h5 = GaussImage(512,40)
ShowDFT(h5)
# image de bruit blanc
h6 = np.random.randn(512,512)
ShowDFT(h6)