def imageFFT(image, show=False): """ FFT de imagem INPUTS: image: imagem original para ser passada para o dominio da frequencia show: parametro para exibição da imagem no domínio da frequencia (padrão: False) OUTPUTS: fftimage: imagem no dominio da frequencia fftshift: shift do dominio da frequencia absfft: módulo da fft para exibir em imagem """ import numpy as np from ImageMedicalLib import info, changeFormat fftimage = np.fft.fft2(image) fftshift = np.fft.fftshift(fftimage) absfft = np.abs(fftshift) absfft = changeFormat.imNormalize(absfft) if show: images = {'absfft': np.uint8(255 * absfft)} info.showImageStyle(1, 1, images, ['absfft']) return fftimage, fftshift, absfft
def LeeFilter(image, kernelLength, show=False): import numpy as np import cv2 from ImageMedicalLib import changeFormat, info if image.dtype == 'uint8': image = changeFormat.uint2double(image) rect = cv2.selectROI(image) cv2.waitKey(0) cv2.destroyAllWindows() c1, c2 = rect[0], rect[0] + rect[2] l1, l2 = rect[1], rect[0] + rect[3] stdRect = np.std(image[l1:l2, c1:c2]) newImage = np.zeros(image.shape) w = np.zeros((kernelLength, kernelLength), dtype=int) w_center = int((w.shape[0]) / 2) for indexrow, frow in enumerate(image[:-(w_center * 2)]): for indexcolumn, fcolumn in enumerate(frow[:-(w_center * 2)]): maskLocal = image[indexrow:1 + indexrow + w_center * 2, indexcolumn:1 + indexcolumn + w_center * 2] meanMask = np.mean(maskLocal + w) k = np.clip(1 - (stdRect / (0.001 + maskLocal.std())), 0, 1) newImage[indexrow + w_center, indexcolumn + w_center] = meanMask + k * ( image[indexrow + w_center, indexcolumn + w_center] - meanMask) if show: info.showImageStyle( 1, 2, { 'I1': changeFormat.im2uint8(image), 'Imean': changeFormat.im2uint8(newImage) }, ['Original', 'Lee Filter']) return newImage
def idealfilter(m, n, fc, filterType='LP', show=False): """ Filtro ideal para dominio da frequencia INPUTS: m: número de linhas n: número de colunas fc: frequencia de corte (0 a 1) filterType: Passa baixa ou passa alta (padrão = LP passa baixa) show: parametro para exibir filtro criado OUTPUTS: H: filtro ideal 2D """ import numpy as np from ImageMedicalLib import changeFormat, info H = np.zeros((m, n), dtype=int) centerX, centerY = int(m / 2), int(n / 2) Do = fc * (0.5 * (centerX * 0.5 + centerY * 0.5)) for i in range(H.shape[0]): for j in range(H.shape[1]): D_uv = ((centerX - i)**2 + (centerY - j)**2)**0.5 if D_uv <= Do and filterType == 'LP': H[i, j] = 1 elif D_uv >= Do and filterType != 'LP': H[i, j] = 1 if show: images = {'H': changeFormat.im2uint8(H)} info.showImageStyle(1, 1, images, ['Butter Mask']) return H
def butterFilter2D(m, n, fc, nPoles, filterType='LP', show=False): """ Filtro butterworth para dominio da frequencia INPUTS: m: número de linhas n: número de colunas fc: frequencia de corte (0 a 1) nPoles: número de polos para filtragem filterType: Passa baixa ou passa alta (padrão = LP passa baixa) show: parametro para exibir filtro criado OUTPUTS: H: filtro butterworth 2D """ import numpy as np from ImageMedicalLib import changeFormat, info if filterType == 'LP': H = np.zeros((m, n)) else: H = np.full((m, n), -1).astype(float) centerX, centerY = int(m / 2), int(n / 2) Do = fc * (0.5 * (centerX * 0.5 + centerY * 0.5)) for i in range(m): for j in range(n): D_uv = ((centerX - i)**2 + (centerY - j)**2)**0.5 H[i, j] = np.abs(H[i, j] + (1 / (1 + (D_uv / Do)**(2 * nPoles)))) if show: images = {'H': changeFormat.im2uint8(H)} info.showImageStyle(1, 1, images, ['Butter Mask']) return H
def imageIFFT(imageFFT, show=False): """ IFFT de imagem INPUTS: imageFFT: imagem no domínio da frequencia show: parametro para exibição da imagem no domínio espacial (padrão: False) OUTPUTS: Ifft: imagem no dominio espacial IfftABS: valor absoluto da imagem no dominio espacial """ import numpy as np from medImUtils import info, changeFormat Ifft = np.fft.ifftshift(imageFFT) Ifft = np.fft.ifft2(Ifft) IfftABS = changeFormat.imNormalize(np.abs(Ifft)) if show: images = {'IfftABS': np.uint8(255 * IfftABS)} info.showImageStyle(1, 1, images, ['IfftABS']) return Ifft, IfftABS
squarePulse = imageio.imread(r'ImagensAulas\PulsoQuadrado1.pgm') plt.figure() plt.get_current_fig_manager().window.showMaximized() fig = plt.gcf() fig.canvas.set_window_title('Square Pulse') plt.imshow(squarePulse,cmap='gray',vmin = 0, vmax=255) plt.axis('off') plt.show() #%% 3 - FFT2 Pulso quadrado fftsquarePulse,fftshiftsquarePulse,absfftsquarePulse = filters.imageFFT(squarePulse) logFFT = np.log(1+fftshiftsquarePulse) logFFTABS = np.abs(logFFT) logFFTABS = changeFormat.im2uint8(changeFormat.imNormalize(logFFTABS)) info.showImageStyle(1,3,{'fftsquarePulse': changeFormat.im2uint8(changeFormat.imNormalize(np.abs(fftsquarePulse))), 'absfftsquarePulse':changeFormat.im2uint8(absfftsquarePulse), 'logFFTABS':logFFTABS}, ['fftsquarePulse','absfftsquarePulse','LogfftsquarePulse']) #%% 4 - Filtro passa baixas de 10% H = np.zeros(squarePulse.shape, dtype = int) centerX, centerY = int((squarePulse.shape[0])/2),int((squarePulse.shape[1])/2) filter_length = centerX*0.5 for i in range (H.shape[0]): for j in range (H.shape[1]): if ((centerX - i)**2 + (centerY - j)**2)**0.5 <= filter_length: H[i,j] = 1 Ffiltrado = changeFormat.im2uint8(absfftsquarePulse)*H info.showImageStyle(1,3,{'absfftsquarePulse':changeFormat.im2uint8(absfftsquarePulse), 'H':changeFormat.im2uint8(H), 'Ffiltrado':Ffiltrado },
#%% 6 - Correlação matriz for indexrow,frow in enumerate(f[:-2]): # enumerate para pegar indices e valores for indexcolumn,fcolumn in enumerate(frow[:-2]): # enumerate para pegar indices e valores corrValue = np.sum(f[indexrow:indexrow+3,indexcolumn:indexcolumn+3] * w) c[indexrow+1,indexcolumn+1] = corrValue #%% 8 - Correlação com ndimage scipy corr = ndimage.correlate(f,w) # Deu bom #%% 11 - Correlação 3x3 mamografia I1 = imageio.imread(r'ImagensAulas\Mamography.pgm') w = np.ones((3,3)) * 1/9 C_3x3 = ndimage.correlate(I1,w) # Deu bom images = {'I1':I1,'C_3x3':C_3x3} info.showImageStyle(1,2,images,['Original','Corr 3x3'],title='Mamo Figure') #%% 11 - Correlação 5x5 mamografia I1 = imageio.imread(r'ImagensAulas\Mamography.pgm') w = np.ones((5,5)) * 1/25 C_5x5 = ndimage.correlate(I1,w) # Deu bom images = {'I1':I1,'C_5x5':C_5x5} info.showImageStyle(1,2,images,['Original','Corr 5x5'],title='Mamo Figure') #%% 11 - Correlação 10x10 mamografia I1 = imageio.imread(r'ImagensAulas\Mamography.pgm') w = np.ones((10,10)) * 1/100 C_10x10 = ndimage.correlate(I1,w) # Deu bom images = {'I1':I1,'C_10x10':C_10x10}
kernelLength = 7 newImage = np.zeros(image.shape) w = np.zeros((kernelLength, kernelLength), dtype=int) w_center = int((w.shape[0]) / 2) for indexrow, frow in enumerate(image[:-(w_center * 2)]): for indexcolumn, fcolumn in enumerate(frow[:-(w_center * 2)]): maskLocal = image[indexrow:1 + indexrow + w_center * 2, indexcolumn:1 + indexcolumn + w_center * 2] meanMask = np.mean(maskLocal + w) k = np.clip(1 - (stdRect / (0.001 + maskLocal.std())), 0, 1) # minimo é zero e maximo é 1 newImage[ indexrow + w_center, indexcolumn + w_center] = meanMask + k * ( image[indexrow + w_center, indexcolumn + w_center] - meanMask) info.showImageStyle(1, 2, { 'I1': changeFormat.im2uint8(I1), 'newImage': changeFormat.im2uint8(newImage) }, ['Original', 'Image Filtered']) #%% Função zero bala Filtro de Lee (esse é mais rapido) newImage = filters.LeeFilter(I1, 9, True) #%% DESAFIO sobel_Image = changeFormat.uint2double(filters.sobel(I1)) meanI1 = changeFormat.uint2double(filters.meanFilterFast(I1, 8)) challenge = meanI1 + sobel_Image * (I1 - meanI1) info.showImageStyle(1, 2, { 'I1': changeFormat.im2uint8(I1), 'challenge': changeFormat.im2uint8(challenge) }, ['Original', 'Challenge'])
#%% 2 - Carregando e filtrando imagem com mediana imri = imageio.imread(r'ImagensAulas\TransversalMRI_salt-and-pepper.pgm') IMRIfiltrada = np.zeros(imri.shape, dtype=int) for indexRow, row in enumerate(imri[:-2]): for indexColumn, column in enumerate(row[:-2]): windowMedian = imri[indexRow:indexRow + 3, indexColumn:indexColumn + 3] windowMedian = windowMedian.reshape(1, -1) windowMedian = np.sort(windowMedian) IMRIfiltrada[indexRow + 1, indexColumn + 1] = windowMedian[0, int((windowMedian.shape[1]) / 2)] #%% 2 - Exibindo imagem images = {'imri': imri, 'IMRIfiltrada': IMRIfiltrada} info.showImageStyle(1, 2, images, ['Original', 'IMRIfiltrada'], title='TransversalMRI_salt-and-pepper') #%% 2 - Histogramas h1 = info.doHistogram(imri, show=False) h2 = info.doHistogram(IMRIfiltrada, show=False) plt.figure() plt.get_current_fig_manager().window.showMaximized() fig = plt.gcf() fig.canvas.set_window_title('Histograms') plt.subplot(121) plt.stem(h1[1, :]) plt.title('Original') plt.subplot(122)