• No se han encontrado resultados

Resultados y discusiones

In document Ruido y calidad en imágenes médicas (página 73-101)

CAPÍTULO 3. SIMULACIÓN DE LOS RUIDOS EN MATLAB

3.3 Resultados y discusiones

A seguir se hizo un conjunto de análisis de la afectación de los ruidos a un grupo de imágenes medicas usando la interface desarrollada aquí, con valores constantes de la media, desviación estándar y densidad (media=0.1, desviación estándar=0.1, densidad=0.1). Los resultados de muestran en la siguiente tabla:

Tabla 3.1: Resultados del análisis de la afectación de los ruidos usando la interface.

Imágenes Distribución (Tipo de ruido) Tamaño de la imagen Afectación Visual a la calidad de la imagen Pot. Imagen SNR (dB) A Poisson 221x300 Moderada 181.3 -16 B Poisson 404x326 Alta 199.9 -23 C Speckle 314x418 Baja 208.17 -12 D Gaussiano 240x240 Moderado 231.5 -11 E Riciano 256x256 Moderado 244 -15

F Salt & Pepper 218x218 Moderada 90.5 -14 La imagen y su similar ruidosa para el penúltimo caso se presentan en la figura 3.1

Esa imagen fue contaminada con el ruido riciano con valores de media y desviación estándar de 0.1. Como podemos ver en la tabla, en unas modalidades de imagen el ruido es más prejudicial que en otras, o sea, se nota más su presencia y como tal afecta más la calidad de las imágenes. Esto se debe a muchos factores como por ejemplo el tipo de ruido que afectan las imágenes en esta modalidad, el proceso de imaginología en sí, etc. En la imagen que se presenta de ejemplo, se puede observar que el ruido afecto la imagen en todos sus aspectos, o sea, disminuyó la visibilidad, contraste, detección de detalles, etc. También podemos observar en la tabla que en algunos casos, aunque la SNR sea menor que en otros casos la afectación a la imagen es mayor. Eso se debe a la calidad de la imagen, pues en algunas modalidades de imagen la imagen tiene mejor calidad que en otras, independientemente del ruido que la afecta después, y como la SNR depende de la potencia de la imagen y del ruido, resulta que en dos modalidades de imagen diferentes, aunque la potencia de ruido sean iguales, el ruido afectara mas a una que a otra.

Es de señalar que una imagen con un nivel de ruido tan alto como la mostrada nunca podrá ser usado en la vida real con propósito de diagnostico pues no presenta calidad suficiente para este propósito y solo llevaría al especialista a un diagnostico erróneo, y solo sirve de ejemplo o para propósito de académico.

CONCLUSIONES Y RECOMENDACIONES

Conclusiones

Este trabajo resulta de referencia para todos aquellos que se dediquen al estudio del tema, o sea, a todos los que se dediquen al estudio del las afectaciones que degradan la calidad de las imágenes médicas en general y a la afectación del ruido en particular, además de dotar a los estudiosos y estudiantes de una herramienta virtual para el análisis de estas imágenes infectando las mismas a partir de la simulación de estos ruidos generados en Matlab. En el desarrollo de este trabajo llegamos a las siguientes conclusiones:

¾ La calidad de las imágenes médicas depende de muchos factores como la modalidad de imagen, el factor humano, etc., pero el ruido es unos de los factores determinantes en esta calidad, y para hablar de la calidad en estas imágenes se tiene que hablar necesariamente del ruido;

¾ En las modalidades como MRI y ultrasonido, el ruido es muy significativo para la determinación de la calidad de las mismas y para un correcto diagnostico por parte del especialista de salud. En comparación con estas técnicas, la radiografía es la que produce imagen con menos ruido;

¾ El tema de calidad en imágenes medicas es un tema muy extenso que no puede ser abarcado en su totalidad en un trabajo de tesis como este;

¾ Los métodos para la evaluación subjetivas de la calidad de la imagen son las que nos brindan un resultado más preciso de la calidad de la imagen pues se saca directamente de la opinión del observador. Sin embargo presentan varios inconvenientes (llevan más tiempo para ser realizadas, ni siempre las opiniones son coincidentes, etc.) a la hora de implementarlas;

¾ Los métodos de evaluación objetivas nos dan una medida de forma más o menos inmediata y por ello sirven para monitorear de forma dinámica la calidad de la imagen, además de presentar otras ventajas si se le compara con las técnicas subjetivas. Sin embargo, son pocas precisas ya que no tienen en cuenta las sensibilidades del sistema visual humano y tratan todas las distorsiones dándoles la misma importancia independientemente de su tipo, localización en la imagen, etc. y por ello no predicen de forma correcta la calidad que realmente es apreciada por el observador.

Recomendaciones

Para un mejor aprovechamiento de este trabajo de diploma se hace la recomendación de los siguientes puntos:

1 En las actividades de práctica de laboratorio de la asignatura Procesamiento de Imágenes y Procesamiento de Imágenes Biomédica incluir el uso de la interface y remeter a los estudiantes a la lectura del trabajo.

2 Realizar una mejora en el software de forma a incluir ruidos presentes en otras modalidades no tratadas aquí.

3 Disponer del trabajo en la red de la facultad de forma a ser usado como material de estudio a los estudiantes y profesores.

4 Incentivar a los estudiantes en el tema mediante realizaciones de seminarios, creación de grupo de investigación, etc., de forma que haya continuidad en la investigación del tema.

REFERENCIAS BIBLIOGRÁFICAS

[1]- A.Carrino, J. (2008). "Digital Image Quality: A Clinical Perspective." 9. Consultado el 20-2-2008. Disponible en www.aapm.org/meetings/02AM/pdf/8469-75819.pdf

[2]- Aguilar, Ana R. (2006). “Modelos Visuales en el Análisis de la Calidad de Imagen”: 181. Consultado el 14-5-08. Disponible en http://scitation.aip.org/getabs/servlet/GetabsServlet [3]- Atencia, J. Nestar, R. (2001). “Aprenda Matlab 6.0 como si estuviera en primero”, 1era edición, Tecnun (Campus Tecnológico de la Universidad de Navarra), San Sebastian. [4]- Boedeker, KL. et al (2007). "Application of the noise power spectrum in modern

diagnostic MDCT: part I. Measurement of noise power spectra and noise equivalent quanta."

Physics in Medicine and Biology Nr 52: 20. Consultado el 23-3-08. Disponible en

www.iop.org/EJ/abstract/0031-9155/52/14/002

[5]- Bronzino, Joseph D. (1995). “Biomedical Engineering Handbook”, 2nda edición, CRC Press in cooperation with IEEE Press, Florida.

[6]- Bronzino, Joseph D. (2006). “Biomedical Engineering: Fundamentals”, CRC Taylor and Francis, New York.

[7]- Cadik, M. y Slavik, P. (2004). "Evaluation of two Principal Approaches to Objective Image Quality Assessment." IEEE Computer Society Press: 6. Consultado el 20-11-2007. Disponible en http://portal.acm.org/citation.cfm.

[8]- González, Rafael C.; Woods, Richards E (2001).”Digital Image Processing”, 2nda edición, Prentice Hall, New Jersey.

[9]- Woods, Richards E, et al (2004). “Digital Image Processing using Matlab ”, Prentice Hall, New Jersey.

[10]- Gudbjartsson, H, y Patz, S. (1995). “The Rician distribution of noisy MRI data”.

Magnetic Resonance in Medicine, 34:910–914. Physics, 12(2):232–233. Consultado el

[11]- Guerrero, D. O. B. Guerrero. “Manual de Interfaz Grafica de Usuario en Matlab”, Universidad Técnica Particular de Loja, Ecuador.

[12]- Guijarro, JA R. et al (2001). "Tomógrafos PET." Revista Española de Medicina

Nuclear, Nr 20: 14. Consultado el 21-2-2008. Disponible en http://db.doyma.es/cgi-

bin/wdbcgi.exe/doyma/mrevista.fulltext

[13]- Gullberg, GT (1987). ”An analytical approach to quantify uniformity artifacts for circular and noncircular detector motion in single photon emission computed tomography imaging.” Med Phys, Nr 14: 105-114. Consultado el 19-12-07. Disponible en

http://scitation.aip.org/getabs/servlet/GetabsServlet

[14]- Herráeza, Miguel G. et al. “Caracterización de un dispositivo de interconexión óptica implementado mediante un SLM de Cristal Líquido Ferroeléctrico”. Consultado el 18-2- 2008. Disponible en

w3.iec.csic.es/ursi/articulos_zaragoza_2000/ursi2000/trabajos/df0303.pdf.

[15]- Jalón, Javier G. et al (1999). “Aprenda Matlab 5.3 como si estuviera en primero”, 1era edición, Universidad de Navarra, San Sebastián.

[16]- Medina, R.; Bellera, J. “Bases del Procesamiento de Imágenes Médicas” Universidad de Los Andes, Facultad de Ingeniería, Grupo de Ingeniería Biomédica de la ULA (GIBULA), Venezuela. Consultado el 21-2-2008. Disponible en http://www.ing.ula.ve/~gibula/.

[17]- Morales, Dr. Rubén O. (2007) “Conferencia 8: Hardware, ruido, calidad y ética asociados al procesamiento de imágenes medicas.” Conferencia de la asignatura Ingeniería Biomédica en Neumann, Universidad Central Marta Abreu de Las Villas, Santa Clara, Cuba. [18]- Ng, Edmund H. O. (2005). "Speckle Noise Reduction via Homomorphic Elliptical Threshold Rotations in the Complex Wavelet Domain": 112. Consultado el 20-11-2007. Disponible en www.uwspace.uwaterloo.ca/handle/10012/812.

[19]-NEMA (1994).” Performance measurements of scintillation cameras.” National

Electrical Manufacturers Association (NEMA), Standards Publication, Washington DC.

Consultado el 19-12-07. Disponible en

www.radfys.lu.se/gu/raf320/nuklearmedicin/NEMA_SCINT.pdf.

[20]-O'Connor, Michael K. et al. "Quality Control of Scintillation Cameras (Planar and SPECT)." Consultado el 1-4-08. Disponible en www.aapm.org/meetings/99AM/pdf/2741- 51264.pdf.

[21]- Papoulis, A. (1984) “Probability, Random Variables and Stochastic Processes”. 2nda edición, McGraw-Hill, Tokyo, Japan.

[22]- Paz, J., y Bosch, A. (2007). "La calidad en las imágenes de Resonancia Magnética Comprimidas con JPEG2000.”: 4. Consultado el 20-11-2007. Disponible en

cencomed.sld.cu/socbio2007/trabajos/pdf/t007.pdf

[23]- R. M. Henkelman (1985). “Measurement of signal intensities in the presence of noise in MR images”. Medical Physics Nr 12, 232.

[24]- Rogers, WL. et al (1982). “Field flood requirements for emission computed tomography with an Anger camera.” J. Nucl Med, Nr 23: 162-168. Consultado el 19-12-07. Disponible en jnm.snmjournals.org/cgi/reprint/23/2/162.pdf

[25]- Russ, John C.”The Image Processing Handbook”, 3era edición, CRC Press with IEEE Press, North Carolina.

[26]- Sijbers, J. et al (1998). "Estimation of the Noise in Magnitude MR Images." Magnetic

Resonance Imaging, Vol.16, Nr 1. Consultado el 29-2-2008. Disponible en

webhost.ua.ac.be/visielab/papers/sijbers/mri98.pdf

[27]-Sprawls, P. y P. D. "The Physical Principles of Medical Imaging." Consultado el 18-

3-08. Disponible en http://www.sprawls.orgresourcesobjectivesNOISE.htm.

[28]- S.Sussman, M. et al. (2004) “Adaptive averaging for improved SNR in Real Time Coronary Artery RMRI”. IEEE Trasactions on Medical Imaging. Vol.23, Nr 8.

[29]- Tejedor, Rafael R. (2002). "Desarrollo de Algoritmos de Optimización Visual en Imágenes Medicas." 244. Consultado el 20-11-2007. Disponible en optica.csic.es/papers/pfc- rredondo.pdf.

[30]- Wang, Z. et al (2003). :”Multi-Scale Structural Similarity For Image Quality

Assessment”. Proceedings of the 37th IEEE Asilomar Conference on Signals, Systems and

Computers, Nov. 9-12.

[31]- Wang, Z. et al (2005). : “Structural Approaches to Image Quality Assessment”,

ANEXO 1

Programa Fuente de la interfaz

function varagout = ruido (varargin) gui_Singleton = 1;

gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @ruido_OpeningFcn, ... 'gui_OutputFcn', @ruido_OutputFcn, ... 'gui_LayoutFcn', [] , ...

'gui_Callback', []); if nargin && ischar(varargin{1})

gui_State.gui_Callback = str2func(varargin{1}); end

if nargout

[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else

gui_mainfcn(gui_State, varargin{:}); end

% --- Executes just before ruido is made visible.

function ruido_OpeningFcn(hObject, eventdata, handles, varargin) axes(handles.axes1);

axis off;

axes(handles.axes2); axis off;

set(handles.media,'String',0); warning off all;

set(handles.desviacion,'String',0); set(handles.densidad,'String',0);

% Choose default command line output for ruido handles.output = hObject;

guidata(hObject, handles);

% --- Outputs from this function are returned to the command line. function varargout = ruido_OutputFcn(hObject, eventdata, handles) % Get default command line output from handles structure

varargout{1} = handles.output;

% --- function Untitled_2_Callback(hObject, eventdata, handles)

[handles.FILENAME, handles.PATHNAME] =

uigetfile('*.jpg;*.bmp;*.tif;*.jp2;*.dcm;*.jpeg','Load Image File'); handles.m=[handles.PATHNAME,handles.FILENAME];

[imori, map] = imread(handles.m); axes(handles.axes1);

imagesc(imori); axis off; colormap gray; handles.img = imori;

guidata(hObject,handles);

% --- function Untitled_5_Callback(hObject, eventdata, handles)

msgbox('Simulador de los ruidos clasicos en imagenes medicas por: Romulo Tebus, 2008','ruido');

% --- function Untitled_6_Callback(hObject, eventdata, handles)

open('ayuda.txt');

% --- Executes on button press in ejecutar.

function ejecutar_Callback(hObject, eventdata, handles) ru = handles.uipanel1;

im = handles.img;

med = str2double(medstr); desvstr = get(handles.desviacion,'String'); desv = str2double(desvstr); densidastr = get(handles.densidad,'String'); densid = str2double(densidastr); var = desv.^2; [r, c] = size(im); Potim = sum(sum(im(:).^2))/(r*c); imzer = zeros(r, c); if (ru==1)

gau = med + desv.*randn(size(im)); imrui = imadd(im,im2uint8(gau)); PotNoi = mean(sum(gau(:).^2)); elseif (ru==2) poi = poissrnd(med,size(im)); imrui = imadd(im,im2uint8(poi)); PotNoi = mean(sum(poi(:).^2)); elseif (ru==3)

imrui = imnoise (im, 'speckle', var); PotNoi = var*(r*c); elseif (ru==4) xr = med + desv.*randn(size(im)); xs = med + desv.*randn(size(im)); x = xr + xs*i; imric = abs(x); imrui = imadd(im,im2uint8(imric)); PotNoi = mean(sum(imric(:).^2)); elseif(ru==5)

imrui = imnoise(im,'salt & pepper',densid); imcon = imnoise(imzer, 'salt & pepper', densid); PotNoi = mean(sum(imcon(:).^2));

end

axes(handles.axes2)

imagesc(imrui); axis off; colormap gray; switch PotNoi case 0 set(handles.snr,'String',num2str(inf)); otherwise snr = 10*log10(Potim/PotNoi); set(handles.snr,'String',num2str(snr)); end handles.ruido = imrui; set(handles.Pim,'String',num2str(Potim)); set(handles.Pnoi,'String',num2str(PotNoi)); guidata(hObject,handles);

% --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))

set(hObject,'BackgroundColor','white'); end

function desviacion_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'),

get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

% --- Executes during object creation, after setting all properties. function media_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))

set(hObject,'BackgroundColor','white'); end

% --- function uipanel1_SelectionChangeFcn(hObject, eventdata, handles) if (hObject == handles.Gaussiano)

r = 1;

elseif (hObject == handles.Poisson) r = 2;

elseif (hObject == handles.Speckle) r = 3;

elseif (hObject == handles.Riciano) r = 4;

elseif (hObject == handles.sandp) r = 5;

end

handles.uipanel1=r; guidata(hObject,handles);

% --- Executes during object creation, after setting all properties. function Pnoi_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))

set(hObject,'BackgroundColor','white'); end

% --- Executes during object creation, after setting all properties. function snr_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))

set(hObject,'BackgroundColor','white'); end

% --- Executes during object creation, after setting all properties. function Pim_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))

set(hObject,'BackgroundColor','white'); end

% --- Executes on button press in pushbutton2.

function pushbutton2_Callback(hObject, eventdata, handles) close all;

% --- function Untitled_3_Callback(hObject, eventdata, handles)

[file,path] = uiputfile('*.jpg','Salvar la imagen con ruido'); out = [path file];

imwrite(handles.ruido,out,'jpg'); guidata(hObject,handles);

ANEXO 2

ANEXO 3

Otras funciones de Matlab usadas en el desarrollo del trabajo imnoise

function b = imnoise(varargin) %IMNOISE Add noise to image.

% J = IMNOISE(I,TYPE,...) Add noise of a given TYPE to the intensity image

% I. TYPE is a string that can have one of these values: %

% 'gaussian' Gaussian white noise with constant % mean and variance

%

% 'localvar' Zero-mean Gaussian white noise % with an intensity-dependent variance %

% 'poisson' Poisson noise %

% 'salt & pepper' "On and Off" pixels %

% 'speckle' Multiplicative noise %

% Depending on TYPE, you can specify additional parameters to IMNOISE. All

% numerical parameters are normalized; they correspond to operations with % images with intensities ranging from 0 to 1.

%

% J = IMNOISE(I,'gaussian',M,V) adds Gaussian white noise of mean M and % variance V to the image I. When unspecified, M and V default to 0 and % 0.01 respectively.

%

% J = imnoise(I,'localvar',V) adds zero-mean, Gaussian white noise of % local variance, V, to the image I. V is an array of the same size as I.

%

% J = imnoise(I,'localvar',IMAGE_INTENSITY,VAR) adds zero-mean, Gaussian % noise to an image, I, where the local variance of the noise is a

% function of the image intensity values in I. IMAGE_INTENSITY and VAR % are vectors of the same size, and PLOT(IMAGE_INTENSITY,VAR) plots the % functional relationship between noise variance and image intensity. % IMAGE_INTENSITY must contain normalized intensity values ranging from 0 % to 1.

%

% J = IMNOISE(I,'poisson') generates Poisson noise from the data instead % of adding artificial noise to the data. If I is double precision, % then input pixel values are interpreted as means of Poisson

% distributions scaled up by 1e12. For example, if an input pixel has % the value 5.5e-12, then the corresponding output pixel will be

% generated from a Poisson distribution with mean of 5.5 and then scaled % back down by 1e12. If I is single precision, the scale factor used is % 1e6. If I is uint8 or uint16, then input pixel values are used

% directly without scaling. For example, if a pixel in a uint8 input % has the value 10, then the corresponding output pixel will be

% generated from a Poisson distribution with mean 10. %

% J = IMNOISE(I,'salt & pepper',D) adds "salt and pepper" noise to the % image I, where D is the noise density. This affects approximately % D*numel(I) pixels. The default for D is 0.05.

%

% J = IMNOISE(I,'speckle',V) adds multiplicative noise to the image I, % using the equation J = I + n*I, where n is uniformly distributed random % noise with mean 0 and variance V. The default for V is 0.04.

%

% Note % ----

% The mean and variance parameters for 'gaussian', 'localvar', and % 'speckle' noise types are always specified as if for a double image % in the range [0, 1]. If the input image is of class uint8 or uint16, % the imnoise function converts the image to double, adds noise

% according to the specified type and parameters, and then converts the % noisy image back to the same class as the input.

%

% Class Support % ---

% For most noise types, I can be uint8, uint16, double, int16, or % single. For Poisson noise, int16 is not allowed. The output

% image J has the same class as I. If I has more than two dimensions % it is treated as a multidimensional intensity image and not as an % RGB image.

%

% Example % ---

% I = imread('eight.tif');

% J = imnoise(I,'salt & pepper', 0.02); % figure, imshow(I), figure, imshow(J) %

% See also RAND, RANDN.

% Copyright 1993-2005 The MathWorks, Inc.

% $Revision: 5.20.4.5 $ $Date: 2005/03/31 16:31:29 $

[a, code, classIn, classChanged, p3, p4] = ParseInputs(varargin{:}); clear varargin;

sizeA = size(a); switch code

case 'gaussian' % Gaussian white noise b = a + sqrt(p4)*randn(sizeA) + p3;

case 'localvar_1' % Gaussian white noise with variance varying locally % imnoise(a,'localvar',v)

% v is local variance array

b = a + sqrt(p3).*randn(sizeA); % Use a local variance array

case 'localvar_2' % Gaussian white noise with variance varying locally % Use an empirical intensity-variance relation

intensity = p3(:); % Use an empirical intensity-variance relation var = p4(:); minI = min(intensity); maxI = max(intensity); b = min(max(a,minI),maxI); b = reshape(interp1(intensity,var,b(:)),sizeA); b = a + sqrt(b).*randn(sizeA);

case 'poisson' % Poisson noise switch classIn

a = round(a*255); case 'uint16' a = round(a*65535); case 'single' a = a * 1e6; % Recalibration case 'double' a = a * 1e12; % Recalibration end a = a(:);

% (Monte-Carlo Rejection Method) Ref. Numerical % Recipes in C, 2nd Edition, Press, Teukolsky, % Vetterling, Flannery (Cambridge Press)

b = zeros(size(a));

idx1 = find(a<50); % Cases where pixel intensities are less than 50 units if (~isempty(idx1)) g = exp(-a(idx1)); em = -ones(size(g)); t = ones(size(g)); idx2 = (1:length(idx1))'; while ~isempty(idx2) em(idx2) = em(idx2) + 1;

t(idx2) = t(idx2) .* rand(size(idx2)); idx2 = idx2(t(idx2) > g(idx2));

end

b(idx1) = em; end

% For large pixel intensities the Poisson pdf becomes % very similar to a Gaussian pdf of mean and of variance

% equal to the local pixel intensities. Ref. Mathematical Methods % of Physics, 2nd Edition, Mathews, Walker (Addison Wesley)

idx1 = find(a >= 50); % Cases where pixel intensities are at least 50 units

if (~isempty(idx1))

b(idx1) = round(a(idx1) + sqrt(a(idx1)) .* randn(size(idx1))); end

b = reshape(b,sizeA);

case 'salt & pepper' % Salt & pepper noise b = a;

x = rand(sizeA);

b(x < p3/2) = 0; % Minimum value

b(x >= p3/2 & x < p3) = 1; % Maximum (saturated) value

case 'speckle' % Speckle (multiplicative) noise b = a + sqrt(12*p3)*a.*(rand(sizeA)-.5);

end

% Truncate the output array data if necessary if strcmp(code,{'poisson'})

switch classIn case 'uint8' b = uint8(b);

case 'uint16' b = uint16(b); case 'single'

b = max(0, min(b / 1e6, 1)); case 'double'

b = max(0, min(b / 1e12, 1)); end

else

b = max(0,min(b,1));

% The output class should be the same as the input class if classChanged, b = changeclass(classIn, b); end end %%% %%% ParseInputs %%%

function [a, code, classIn, classChanged, p3, p4, msg] = ParseInputs(varargin)

% Initialization p3 = []; p4 = []; msg = '';

% Check the number of input arguments. iptchecknargin(1,4,nargin,mfilename); % Check the input-array type.

a = varargin{1};

iptcheckinput(a, {'uint8','uint16','double','int16','single'}, {}, mfilename, ...

'I', 1); % Change class to double classIn = class(a); classChanged = 0; if ~isa(a, 'double') a = im2double(a); classChanged = 1; else

% Clip so a is between 0 and 1. a = max(min(a,1),0);

end

% Check the noise type. if nargin > 1

if ~ischar(varargin{2})

eid = sprintf('Images:%s:invalidNoiseType',mfilename); msg = 'TYPE must be a character string.';

error(eid,'%s',msg); end

% Preprocess noise type string to detect abbreviations. allStrings = {'gaussian', 'salt & pepper', 'speckle',... 'poisson','localvar'};

idx = find(strncmpi(varargin{2}, allStrings, numel(varargin{2}))); switch length(idx)

case 0

eid = sprintf('Images:%s:unknownNoiseType',mfilename); msg = sprintf('Unknown noise type: ''%s''.', varargin{2}); error(eid,'%s',msg);

case 1

code = allStrings{idx}; otherwise

eid = sprintf('Images:%s:ambiguousNoiseType',mfilename); msg = sprintf('Ambiguous noise type: ''%s''.', varargin{2}); error(eid,'%s',msg);

end else

code = 'gaussian'; % default noise type end

switch code case 'poisson' if nargin > 2

eid = sprintf('Images:%s:tooManyPoissonInputs',mfilename); msg = 'Too many inputs for ''poisson'' noise.';

error(eid,'%s',msg); end

if strcmp(classIn, 'int16')

eid = sprintf('Images:%s:badClassForPoisson', mfilename);

error(eid, 'int16 input not allowed for the ''poisson'' option.'); end case 'gaussian' p3 = 0; % default mean p4 = 0.01; % default variance if nargin > 2 p3 = varargin{3}; if ~isRealScalar(p3) eid = sprintf('Images:%s:invalidMean',mfilename);

msg = 'For ''gaussian'' noise, M must be a real scalar.'; error(eid,'%s',msg); end end if nargin > 3 p4 = varargin{4}; if ~isNonnegativeRealScalar(p4) eid = sprintf('Images:%s:invalidVariance',mfilename);

msg = 'For ''gaussian'' noise, V must be a real nonnegative scalar.'; error(eid,'%s',msg); end end if nargin > 4 eid = sprintf('Images:%s:tooManyGaussianInputs',mfilename); msg = 'Too many inputs for ''gaussian'' noise.';

error(eid,'%s',msg); end

case 'salt & pepper'

if nargin > 2

p3 = varargin{3};

if ~isNonnegativeRealScalar(p3) || (p3 > 1)

eid = sprintf('Images:%s:invalidNoiseDensity',mfilename); msg1 = 'For ''salt & pepper'' noise, D must be a real nonnegative '; msg2 = 'scalar less than or equal to 1.';

msg = sprintf('%s\n%s',msg1,msg2); error(eid,'%s',msg); end if nargin > 3 eid = sprintf('Images:%s:tooManySaltAndPepperInputs',mfilename); msg = 'Too many inputs for ''salt & pepper'' noise.';

error(eid,'%s',msg); end end case 'speckle' p3 = 0.05; % default variance if nargin > 2 p3 = varargin{3}; if ~isNonnegativeRealScalar(p3) eid = sprintf('Images:%s:invalidVariance',mfilename);

msg = 'For ''speckle'' noise, V must be a nonnegative real scalar.'; error(eid,'%s',msg); end end if nargin > 3 eid = sprintf('Images:%s:tooManySpeckleInputs',mfilename); msg = 'Too many inputs for ''speckle'' noise.';

error(eid,'%s',msg); end case 'localvar' if nargin < 3 eid = sprintf('Images:%s:toofewLocalVarInputs',mfilename); msg = 'Too few inputs for ''localvar'' noise.';

error(eid,'%s',msg); elseif nargin == 3 % IMNOISE(a,'localvar',v) code = 'localvar_1'; p3 = varargin{3}; if ~isNonnegativeReal(p3) || ~isequal(size(p3),size(a)) eid = sprintf('Images:%s:invalidLocalVariance',mfilename); msg1 = 'For the ''localvar'' noise syntax, V must contain '; msg2 = 'only nonnegative real values and be the same size as A.'; msg = sprintf('%s\n%s',msg1,msg2); error(eid,'%s',msg); end elseif nargin == 4 % IMNOISE(a,'localvar',IMAGE_INTENSITY,NOISE_VARIANCE) code = 'localvar_2'; p3 = varargin{3}; p4 = varargin{4};

if ~isNonnegativeRealVector(p3) || (any(p3) > 1)

eid = sprintf('Images:%s:invalidImageIntensity',mfilename); msg1 = 'For ''localvar'' noise, IMAGE_INTENSITY must be a '; msg2 = 'nonnegative real vector less than or equal to 1.'; msg = sprintf('%s\n%s',msg1,msg2); error(eid,'%s',msg); end if ~isNonnegativeRealVector(p4) eid = sprintf('Images:%s:invalidLocalVariance',mfilename); msg1 = 'For ''localvar'' noise, NOISE_VARIANCE must be a '; msg2 = 'nonnegative real vector.';

msg = sprintf('%s\n%s',msg1,msg2); error(eid,'%s',msg); end if ~isequal(size(p3),size(p4)) eid = sprintf('Images:%s:invalidSize',mfilename); msg1 = 'For ''localvar'' noise, IMAGE_INTENSITY and '; msg2 = 'NOISE_VARIANCE must be the same size.';

msg = sprintf('%s\n%s',msg1,msg2); error(eid,'%s',msg); end else eid = sprintf('Images:%s:tooManyLocalVarInputs',mfilename); msg = 'Too many inputs for ''localvar'' noise.';

error(eid,'%s',msg); end end %%% %%% isReal %%% function t = isReal(P)

% isReal(P) returns 1 if P contains only real % numbers and returns 0 otherwise.

%

isFinite = all(isfinite(P(:)));

t = isreal(P) && isFinite && ~isempty(P);

%%%

%%% isNonnegativeReal %%%

function t = isNonnegativeReal(P)

% isNonnegativeReal(P) returns 1 if P contains only real % numbers greater than or equal to 0 and returns 0 otherwise.

In document Ruido y calidad en imágenes médicas (página 73-101)

Documento similar