Sei sulla pagina 1di 12

Some useful functions to get started with image processing using MATLAB imread

Read image from graphics file Syntax A = imread(filename, fmt) Description A = imread(filename, fmt) reads a grayscale or color image from the file specified by the string filename. If the file is not in the current folder, or in a folder on the MATLAB path, specify the full pathname. The text string fmt specifies the format of the file by its standard file extension. For example, specify 'gif' for Graphics Interchange Format files. To see a list of supported formats, with their file extensions, use the imformats function. If imread cannot find a file named filename, it looks for a file named filename.fmt. The return value A is an array containing the image data. If the file contains a grayscale image, A is an Mby-N array. If the file contains a truecolor image, A is an M-by-N-by-3 array. For TIFF files containing color images that use the CMYK color space, A is an M-by-N-by-4 array. The file must be in the current directory or on the MATLAB path.

imwrite
Write image to graphics file Syntax imwrite(A,filename,fmt) Description imwrite(A,filename,fmt) writes the image A to the file specified by filename in the format specified by fmt. A can be an M-by-N (grayscale image) or M-by-N-by-3 (truecolor image) array, but it cannot be an empty array. For TIFF files, A can be an M-by-N-by-4 array containing color data that uses the CMYK color

space. For GIF files, A can be an M-by-N-by-1-by-P array containing grayscale or indexed images RGB images are not supported. filename is a string that specifies the name of the output file. REMEMBER: The file must be in the current directory or on the MATLAB path.

imshow
Display image Syntax imshow(I) Description imshow(I) displays the grayscale image I. imshow(I,[low high]) displays the grayscale image I, specifying the display range for I in [low high]. The value low (and any value less than low) displays as black; the value high (and any value greater than high) displays as white. Values in between are displayed as intermediate shades of gray, using the default number of gray levels. If you use an empty matrix ([]) for [low high], imshow uses [min(I(:)) max(I(:))]; that is, the minimum value in I is displayed as black, and the maximum value is displayed as white. imshow(RGB) displays the truecolor image RGB. imshow(BW) displays the binary image BW. imshow displays pixels with the value 0 (zero) as black and pixels with the value 1 as white.

imresize
Resize image Syntax B = imresize(A, scale)

B = imresize(A, [mrows ncols]) Description B = imresize(A, scale) returns image B that is scale times the size of A. The input image A can be a grayscale, RGB, or binary image. If scale is between 0 and 1.0, B is smaller than A. If scale is greater than 1.0, B is larger than A. B = imresize(A, [mrows ncols]) returns image B that has the number of rows and columns specified by [mrows ncols]. Either NUMROWS or NUMCOLS may be NaN, in which case imresize computes the number of rows or columns automatically to preserve the image aspect ratio.

mat2gray
Convert matrix to grayscale image Syntax I = mat2gray(A, [amin amax]) I = mat2gray(A) Description I = mat2gray(A, [amin amax]) converts the matrix A to the intensity image I. The returned matrix I contains values in the range 0.0 (black) to 1.0 (full intensity or white). amin and amax are the values in A that correspond to 0.0 and 1.0 in I. I = mat2gray(A) sets the values of amin and amax to the minimum and maximum values in A.

graythresh
Global image threshold using Otsu's method Syntax level = graythresh(I)

[level EM] = graythresh(I) Description level = graythresh(I) computes a global threshold (level) that can be used to convert an intensity image to a binary image with im2bw. level is a normalized intensity value that lies in the range [0, 1].

im2bw
Convert image to binary image, based on threshold Syntax BW = im2bw(I, level) Description BW = im2bw(I, level) converts the grayscale image I to a binary image. The output image BW replaces all pixels in the input image with luminance greater than level with the value 1 (white) and replaces all other pixels with the value 0 (black). Specify level in the range [0,1]. This range is relative to the signal levels possible for the image's class. Therefore, a level value of 0.5 is midway between black and white, regardless of class. To compute the level argument, you can use the function graythresh. If you do not specify level, im2bw uses the value 0.5. If the input image is not a grayscale image, im2bw converts the input image to grayscale, and then converts this grayscale image to binary by thresholding.

hist
Histogram plot GUI Alternatives To graph selected variables, use the Plot Selector in the Workspace Browser. Syntax n = hist(Y)

n = hist(Y,x) Description A histogram shows the distribution of data values. n = hist(Y) bins the elements in vector Y into 10 equally spaced containers and returns the number of elements in each container as a row vector. If Y is an m-by-p matrix, hist treats the columns of Y as vectors and returns a 10-by-p matrix n. Each column of n contains the results for the corresponding column of Y. No elements of Y can be complex or of type integer. n = hist(Y,x) where x is a vector, returns the distribution of Y among length(x) bins with centers specified by x. For example, if x is a 5-element vector, hist distributes the elements of Y into five bins centered on the x-axis at the elements in x, none of which can be complex. Note: use histc if it is more natural to specify bin edges instead of centers.

Removing Noise from Images


The MATLAB toolbox provides the imnoise function, which you can use to add various types of noise to an image. The examples in this section use this function.

imnoise Add noise to image Syntax J = imnoise(I,type) J = imnoise(I,type,parameters) J = imnoise(I,'gaussian',m,v) J = imnoise(I,'poisson') J = imnoise(I,'salt & pepper',d) J = imnoise(I,'speckle',v)

Description J = imnoise(I,type) adds noise of a given type to the intensity image I. type is a string that can have one of these values. 'gaussian' 'localvar' 'poisson' 'salt & pepper' 'speckle' Gaussian white noise with constant mean and variance Zero-mean Gaussian white noise with an intensity-dependent variance Poisson noise On and off pixels Multiplicative noise

J = imnoise(I,type,parameters) 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. The default is zero mean noise with 0.01 variance. 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.

Removing Noise By Linear Filtering You can use linear filtering to remove certain types of noise. Certain filters, such as averaging or Gaussian filters, are appropriate for this purpose. For example, an averaging filter is useful for removing grain noise from a photograph. Because each pixel gets set to the average of the pixels in its neighborhood, local variations caused by grain are reduced.

Removing Noise By Median Filtering Median filtering is similar to using an averaging filter, in that each output pixel is set to an average of the pixel values in the neighborhood of the corresponding input pixel. However, with median filtering, the value of an output pixel is determined by the median of the neighborhood pixels, rather than the mean. The median is much less sensitive than the mean to extreme values (called outliers). Median filtering is therefore better able to remove these outliers without reducing the sharpness of the image. The

medfilt2 function implements median filtering.

The following example compares using an averaging filter and medfilt2 to remove salt and pepper noise. This type of noise consists of random pixels' being set to black or white (the extremes of the data range). In both cases the size of the neighborhood used for filtering is 3-by-3. Read in the image and display it. I = imread('filename.extension'); imshow(I) Add noise to it and display it. J = imnoise(I,'salt & pepper',0.02); imshow(J) Filter the noisy image with an averaging filter and display the results. K = filter2(fspecial('average',3),J)/255; imshow(K)

Now use a median filter to filter the noisy image and display the results. Notice that medfilt2 does a better job of removing noise, with less blurring of edges. L = medfilt2(J,[3 3]); imshow(L)

Deblurring with the Wiener Filter Use the

deconvwnr function to deblur an image using the Wiener filter. Wiener deconvolution can

be used effectively when the frequency characteristics of the image and additive noise are known, to at least some degree. In the absence of noise, the Wiener filter reduces to the ideal inverse filter.

deconvwnr Deblur image using Wiener filter Syntax J = deconvwnr(I,PSF,NSR) Description J = deconvwnr(I,PSF,NSR) deconvolves image I using the Wiener filter algorithm, returning deblurred image J. Image I can be an N-dimensional array. PSF is the point-spread function with which I was convolved. NSR is the noise-to-signal power ratio of the additive noise. NSR can be a scalar or an array of the same size as I. Specifying 0 for the NSR is equivalent to creating an ideal inverse filter.

fft
Discrete Fourier transform Syntax Y = fft(X) Y = fft(X,n)

Y = fft(X,[],dim) Y = fft(X,n,dim) Definition The functions Y=fft(x) and y=ifft(X) implement the transform and inverse transform pair given for vectors of length by:

where

is an Nth root of unity. Description Y = fft(X) returns the discrete Fourier transform (DFT) of vector X, computed with a fast Fourier transform (FFT) algorithm. If X is a matrix, fft returns the Fourier transform of each column of the matrix. If X is a multidimensional array, fft operates on the first nonsingleton dimension. Y = fft(X,n) returns the n-point DFT. If the length of X is less than n, X is padded with trailing zeros to length n. If the length of X is greater than n, the sequence X is truncated. When X is a matrix, the length of the columns is adjusted in the same manner. Y = fft(X,[],dim) and Y = fft(X,n,dim) applies the FFT operation across the dimension dim

dct
Discrete cosine transform (DCT) Syntax y = dct(x) y = dct(x,n) Description y = dct(x) returns the unitary discrete cosine transform of x

where

N is the length of x, and x and y are the same size. If x is a matrix, dct transforms its columns. The series is indexed from n = 1 and k = 1 instead of the usual n = 0 and k = 0 because MATLAB vectors run from 1 to N instead of from 0 to N- 1. y = dct(x,n) pads or truncates x to length n before transforming. The DCT is closely related to the discrete Fourier transform. You can often reconstruct a sequence very accurately from only a few DCT coefficients, a useful property for applications requiring data reduction.

dct2 Syntax

2-D discrete cosine transform B = dct2(A) B = dct2(A,m,n)

Description

B = dct2(A) returns the two-dimensional discrete cosine transform of A. The matrix B is the same size as A and contains the discrete cosine transform coefficients B(k1,k2).

B = dct2(A,m,n) pads the matrix A with 0's to size m-by-n before transforming. If m or n is smaller than the corresponding dimension of A, dct2 truncates A.

Detecting Edges Using the edge Function


edge returns a binary image containing 1's where edges are found and 0's elsewhere. The most powerful edge-detection method that edge provides is the Canny method. The Canny method differs from the other edge-detection methods in that it uses two different thresholds (to detect strong and weak edges), and includes the weak edges in the output only if they are connected to strong edges. This method is therefore less likely than the others to be fooled by noise, and more likely to detect true weak edges.

edge
Find edges in grayscale image Syntax BW = edge(I) BW = edge(I,'sobel') BW = edge(I,'sobel',thresh) BW = edge(I,'prewitt') BW = edge(I,'prewitt',thresh) BW = edge(I,'roberts') BW = edge(I,'roberts',thresh) BW = edge(I,'canny') BW = edge(I,'canny',thresh)

The following example illustrates the power of the Canny edge detector by showing the results of applying the Sobel and Canny edge detectors to the same image:

Read image and display it. I = imread('coins.png'); imshow(I)

Apply the Sobel and Canny edge detectors to the image and display them. BW1 = edge(I,'sobel'); imshow(BW1) BW2 = edge(I,'canny'); imshow(BW2)

Potrebbero piacerti anche