EX.NO: DISPLAY OF GRAYSCALE IMAGES DATE: AIM: To write a MATLAB program a) To read and display an image. b) To perform data type conversion to 8 bit, 16 bit, 32 bit and double data types. c) To perform file format conversion in jpg, jpeg, png, bmp and tiff formats. d) To perform arithmetic and logical operations on different images. SOFTWARE USED: MATLAB Version 2013. THEORY: Types and classes of images: Name Double Single Uint8 Unit16 Uint32 Description Double precision, floating point numbers in approximate range ±10308(8 bytes per element) Single precision, floating point with value in range ±10308(4 bytes per element) Unsigned 8 bit integer[0, 255] (1 byte per element) Unsigned 16 bit integer[0 , 65536] (2 byte/element) Unsigned 32 bit integer[0 , 4294967295] (4 byte/element) Characters (2 bytes/element) Values are 0 or 1 (1 byte/element) Char Logical Image types: The toolbox supports 4 types of images: Grayscale Binary Indexed RGB Grayscale image, also called gray level image, is a data matrix whose values represent shades of grey. Binary image: Each pixel assumes one of only two discrete values 1 or 0. A binary image is started as a logical array of 0s or 1s. Thus, a numeric array is converted into binary using function ‘logical’. BW refers to binary images. Indexed image: It consists of an array and a colourmap matrix. The pixel values in the array are direct indices into a colourmap. This uses the variable X to refer to the array and map refers to the colourmap. The colourmap matrix is an m-‐by-‐3 array of class ‘double’ containing floating point values in the range [0,1]. Each row of a map specifies red, green and blue components of a single colour. RGB images use three numbers for each pixel, allowing possible use of millions of colours within the image at the cost of requiring three times as much space as grayscale images do. Image files and formats: They are the standardized means of organizing and storing digital images. a) JPEG/JFIF: Joint Photographic Experts Group is a compression method. JPEG compressed images are actually stored in JFIF (JPEG File Interchange Format). JPEG in most cases is a lossy compression. JPEG/JFIF filename extension is JPG or JPEG b) TIFF (Tagged Image File Formats): It is a flexible format that manually saves 8 bits or 16 bits per colour(RGB) for 24 bits and 48 bits total. Filename extension: TIFF or TIF E.g.: Digital Camera Images c) GIF (Graphics Interchange Format): It is limited to an 8 bit palette or 256 colours. This makes GIF format suitable for simplediagrams, shapes etc. Supports animation Lossless compression that is more effective d) PNG(Portable Network Graphics): Supports true colour(16 million) The lossless PNG format is best suited for editing pictures. The lossy formats like PNG are best suited for final distribution. e) BMP (Bitmap File Format): Handles graphics files within MS Windows OS BMP files are uncompressed, hence they are large SYNTAXES USED: IMREAD IMREAD reads image from graphics file. a=imread(‘filename.fmt’) reads a grayscale or color image from the file specified by the string FILENAME. The text string ‘fmt’ specifies the format of the file by its standard file extension. The return value A is an array containing the image data. If the file contains a grayscale image, A is an M-‐by-‐N array. If the file contains a true color 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. IMSHOW IMSHOW displays image in Handle Graphics. a=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 default number of gray levels. if you use an empty matrix([]) for[low high], imshow uses [min(I(:))]; that is, the min value in I is displayed as black, and the max value is displayed as white. imshow(rgb) displays the true color image rgb. imshow(bw) displays the binary image bw. ‘imshow’ displays pixels with 0 as black and pixels with 1 as white. IMRESIZE It resizes image. b=imresize(a,scale) returns an image that is scale times the size of a, which is grayscale, rgb, or binary image. b=imresize(a,[numrows numcols]) resizes the image so that it has specified number of rows and columns. either numrows or numcols may be NaN, in which case ‘imresize’ computes the number of rows or columns automatically in order to preserve the image aspect ratio. IMFINFO IMFINFO displays information about graphics file. a=imfinfo(‘filename.fmt’) returns a structure whose fields contain information about an image in a graphics file. It displays the information about file size, height, width, resolution, image type, etc. RGB2GRAY Converts RGB image or colormap to grayscale. ‘rgb2gray’ converts RGB images to grayscale by eliminating the hue and saturation information while retaining the luminance. IMADD Adds one image from another or adds constant to an image. Z=imadd(X,Y) adds each element in array X with the corresponding element in array Y and returns the sum in the corresponding element of the output array Z. X and Y are real, non-‐sparse numeric arrays with the same size and class, or Y is a scalar double. Z If X and Y are integer arrays. If X is an integer array. If X and Y are real numeric arrays with the same size and class. IMDIVIDE Division of the image by a constant value Z = imdivide(X. in which case Z is double. If X and Y are numeric arrays of the same size and class. or Y is a double scalar. If X is an integer array.Y) multiplies each element in array X by the corresponding element in array Y and returns the product in the corresponding element of the output array Z. IMMULTIPLY Multiplication of two images or multiplication of an image by a constant Z = immultiply(X. Z. and fractional values are rounded. Z has the same size and class as X and Y. non-‐sparse numeric arrays with the same size and class. If X is numeric and Y is logical. unless X is logical. then Z has the same size and class as X. elements in the output that exceed the range of the integer type are truncated. . in which case Z is double. X and Y are real. If X is an integer array. has the same size and class as X unless X is logical. If X is logical and Y is numeric. If X is a numeric array and Y is a scalar double. ‘immultiply’ computes each element of Z individually in double-‐precision floating point. elements of the output that exceed the range of the integer type are truncated.has the same size and class as X./Y instead of imdivide. you can use the expression X. in which case Z is double. then Z has the same size and class as Y. then elements of Z exceeding the range of the integer type are truncated.*Y instead of immultiply. then Z has the same size and class as X. X and Y are real. elements in the output that exceed the range of integer type are truncated. If X and Y are numeric arrays of the same size and class. and fractional values are rounded. then Z has the same size and class as X. and fractional values are rounded. unless X is logical.Y) divides each element in the array X by the corresponding element in array Y and returns the result in the corresponding element of the output array Z. The array returned.Y) subtracts each element in array Y from the corresponding element in array X and returns the difference in the corresponding element of the output array Z. or Y can be a scalar double. you can use the expression X. non-‐sparse numeric arrays of the same size and class. IMSUBTRACT Subtract one image from another or subtract constant from image Z = imsubtract(X. and fractional values are rounded. FUNCTIONS bitand Find logical AND cmp Find logical NOT bitor Find logical OR bitxor Logical exclusive-‐OR . respectively. Certain MATLAB® functions and operators return logical values to indicate fulfillment of a condition. You can use those logical values to index into an array or execute conditional code.LOGICAL OPERATIONS True or false (Boolean) conditions The logical data type represents true or false states using the numbers 1 and 0. uint16=im2uint16(img1). title('Rice').png') info=imfinfo('convert. whos('tif'). figure.png').tif'). whos('img2').tif') ARITHMETIC OPERATION: img2=imread('cameraman. subplot(221).'convert. whos('uint16'). imwrite(img1. clc. inf=imfinfo('rice.tif'). whos('img1'). . subplot(224). subplot(223). subplot(332). imshow(img2). subplot(222). whos('c'). title('Tif'). imshow(add). double=im2double(img1). title('Camera Man'). title('double').img2). imshow(uint16).tif'). imshow(tif). img1=imread('rice. tif=imread('convert.TYPE AND FILE CONVERSION clear. imshow(img1). subplot(333). add=imadd(img1. imshow(double). title('uint16'). title('uint8'). subplot(331). imshow(img1). title('Added'). subplot(338). subplot(337). imshow(mul1). whos('div2'). title('Subtracted'). sub=imsubtract(img1. mul1=immultiply(img1.0.2). imshow(or). div1=imdivide(img1. im3=imresize(im2. title('Divided by 0. subplot(334).png').[256 256]). imshow(div1).img2).0.im3). title('AND'). title('Multiply by 0.png'). whos('mul2').2'). title('OR'). subplot(233). div2=imdivide(img1.2). whos('sub'). subplot(234). and=bitand(im1. imshow(div2). imshow(mul2). whos('or*'). mul2=immultiply(img1. whos('div1'). title('Multiply by 2'). subplot(335).2). whos('mul1').2).2'). LOGICAL OPERATION: im1=imread('Rice. . whos('and*'). imshow(and).whos('add'). title('Divided by 2'). subplot(336). imshow(sub).im3). or=bitor(im1. im2=imread('Coins. title('Image2'). imshow(im3). title('Image1'). imshow(xor). subplot(231). whos('xor*').im3). imshow(im1). subplot(235).xor=bitxor(im1. . title('XOR'). subplot(232). OBSERVATION: Name Size Bytes Class Attributes img1 256x256 65536 uint8 Name Size Bytes Class Attributes uint16 256x256 131072 uint16 Name Size Bytes Class Attributes tif 256x256 65536 uint8 inf = Filename: [1x62 char] FileModDate: '26-‐Jan-‐2003 01:03:06' FileSize: 44607 Format: 'png' FormatVersion: [] Width: 256 Height: 256 BitDepth: 8 ColorType: 'grayscale' FormatSignature: [137 80 78 71 13 10 26 10] Colormap: [] Histogram: [] InterlaceType: 'none' Transparency: 'none' SimpleTransparencyData: [] BackgroundColor: [] RenderingIntent: [] Chromaticities: [] Gamma: [] XResolution: [] YResolution: [] ResolutionUnit: [] XOffset: [] YOffset: [] OffsetUnit: [] . tif' FileModDate: '17-‐Sep-‐2015 10:29:31' FileSize: 66250 Format: 'tif' FormatVersion: [] Width: 256 Height: 256 BitDepth: 8 ColorType: 'grayscale' FormatSignature: [73 73 42 0] ByteOrder: 'little-‐endian' NewSubFileType: 0 BitsPerSample: 8 Compression: 'PackBits' PhotometricInterpretation: 'BlackIsZero' StripOffsets: [8 8265 16474 24733 32987 41198 49461 57732] SamplesPerPixel: 1 RowsPerStrip: 32 StripByteCounts: [8257 8209 8259 8254 8211 8263 8271 8263] XResolution: 72 YResolution: 72 ResolutionUnit: 'Inch' Colormap: [] PlanarConfiguration: 'Chunky' TileWidth: [] TileLength: [] . SignificantBits: [] ImageModTime: '27 Dec 2002 19:57:12 +0000' Title: [] Author: [] Description: 'Rice grains' Copyright: 'Copyright The MathWorks.' CreationTime: [] Software: [] Disclaimer: [] Warning: [] Source: [] Comment: [] OtherText: [] info = Filename: '\\psf\Home\Documents\MATLAB\convert. Inc. 0100 MaxSampleValue: 255 MinSampleValue: 0 Thresholding: 1 Offset: 65996 Name Size Bytes Class Attributes img2 256x256 65536 uint8 Name Size Bytes Class Attributes add 256x256 65536 uint8 Name Size Bytes Class Attributes sub 256x256 65536 uint8 Name Size Bytes Class Attributes div1 256x256 65536 uint8 Name Size Bytes Class Attributes div2 256x256 65536 uint8 Name Size Bytes Class Attributes mul1 256x256 65536 uint8 Name Size Bytes Class Attributes mul2 256x256 65536 uint8 Name Size Bytes Class Attributes . TileOffsets: [] TileByteCounts: [] Orientation: 1 FillOrder: 1 GrayResponseUnit: 0. or 256x256 65536 uint8 Name Size Bytes Class Attributes and 256x256 65536 uint8 OUTPUT: FILE CONVERSION . ARITHMETIC OPERATION LOGICAL OPERATION: . The threshold image g(x.y) is defined as Single threshold Multiple Threshold Thresholding may be viewed as a operation involving the function T of the form Where a.y) for which f(x.NO: MASKING AND THRESHOLDING DATE-‐ AIM: To write a MATLAB program a) To read and display an image. p(x.y) consists of a light object on a dark background in such a way that object and background pixels have intensity levels grouped into two dominant modes. Then any point (x.y) .y) ≥ T is called object point. SOFTWARE USED: MATLAB Version 2013. Here.y) = gray level of point (x. b) To create a grayscale image and perform masking operation c) To perform thresholding operation. Suppose an image f(x.EX. THEORY THRESHOLDING Thresholding is a method of image segmentation based on the intensity histogram of the image. f(x.y) b. otherwise the point is called background point.y) = local property of the point (x. it is easier to extract by selecting a threshold T that separates these modes. y) ie. x. To get a closer view of the pixels displayed in the tool. the gray level values.y). . the gray level values & the local properties. The Pixel Region tool opens a separate figure window containing an extreme close-‐up view of a small region of pixels in the target image.0 in I.0 (black) to 1. I = mat2gray(A) sets the values of amin and amax to the minimum and maximum values in A. Values less than amin become 0. and values greater than amax become 1. The Pixel Region rectangle defines the area of the target image that is displayed in the Pixel Region tool.c. MAT2GRAY I = mat2gray(A. You can move this rectangle over the target image using the mouse to view different regions. the local properties as well as the spatial coordinates of the point the threshold is called Dynamic or Adaptive Threshold SYNTAXES USED: IMREAD IMSHOW IMPIXEL REGION impixelregion creates a Pixel Region tool associated with the image displayed in the current figure.y) & x.___) performs the operation on a GPU. use the zoom buttons on the Pixel Region tool toolbar or change the size of the Pixel Region rectangle using the mouse. p(x.y = the spatial coordinates of the point When T depends only on f(x.0 (full intensity or white).0. called the target image.y) ie.y ie. amin and amax are the values in A that correspond to 0.0. the threshold is called Local Threshold When T depends only f(x. [amin amax]) converts the matrix A to the intensity image I. the threshold is called Global Threshold When T depends only on both f(x.y) and p(x.0 and 1. gpuarrayI = mat2gray(gpuarrayA. only the gray level values. The returned matrix I contains values in the range 0. subplot(235). subplot(234). ma1=im2double(ma). THRESHOLDING a=imread('coins. . subplot(221). imhist(a). subplot(233). imshow(co1). imshow(b1). b1=a>99.j)=1. BW1=im2bw(b1.ma1).png'). for i=107:140. ma=zeros(256. imshow(fi). level=graythresh(a). imshow(BW). end subplot(222). imshow(a). whos('co1*'). ma1(i. imshow(ma1). title('Histogram').4667). title('Coins'). subplot(223). title('Using Greythresh').0. imshow(BW1). subplot(231). co1=im2double(co).level). subplot(232). title('Using Threshold Value').MASKING OF IMAGE co=imread('Rice. title('Using Histogram'). title('Coins'). title('Mask Unprocessed'). BW=im2bw(a. display(level).256).png'). fi=immultiply(co1. j=16:28. OBSERVATION: MASKING THRESHOLDING . When unspecified. 'gaussian' Gaussian white noise with constant mean and variance 'poisson' Poisson noise 'salt & pepper' On and off pixels 'speckle' Multiplicative noise Types: Gaussian: Gaussian white noise with constant mean and variance. J = IMNOISE (I.V) adds Gaussian white noise of mean M and variance V to the image I.EX. SYNTAX USED: IMNOISE Add noise to image.M. M and V default from 0 to 0.01 respectively. TYPE.NO: ADDITION OF NOISES AND FILTERING DATE: AIM: To write a MATLAB program a) To add the following noises to an image: Salt & pepper Speckle Poisson Gaussian b) To filter an image using the following types of filter: Median Weiner Gaussian Laplacian SOFTWARE REQUIRED: MATLAB Version 2013.'gaussian'. J = IMNOISE(I. .…) Add noise of a given TYPE to the intensity image. Salt And pepper: "On and Off" pixels. Poisson: Poisson noise. Each output pixel contains the median value in the M-‐by-‐N neighborhood around the corresponding pixel in the input image. if a pixel in a uint8 input has the value 10.[M N]) performs median filtering of the matrix A in two dimensions. MEDFILT2 pads the image with zeros on the edges.J = IMNOISE(I. Replace h in this syntax with g for Gaussian filter.H) filters the multidimensional array A with the multidimensional filter H.05. the scale factor used is 1e6. then the corresponding output pixel will be generated from a Poisson distribution with mean 10. then input pixel values are interpreted as means of Poisson distributions scaled up by 1e12.'speckle'. If I is single precision. B has the same size and class as A. Wiener: WIENER2 2-‐D adaptive noise-‐removal filtering. If I is uint8 or uint16. Types of filters Median: MEDFILT2 2-‐D median filtering. IfI is double precision. so the median values for the points within [M N]/2 of the edges may appear distorted. The default for D is 0. Speckle: Multiplicative noise. J = IMNOISE(I. For example. This affects approximately D*numel(I) pixels. A can be logical or it can be a nonsparse numeric array of any class and dimension. where n is uniformly distributed random noise with mean 0 and variance V. ‘poisson') generates Poisson noise from the data instead of adding artificial noise to the data. l for laplacian filter. if an input pixel has the value 5. then input pixel values are used directly without scaling. . then the corresponding output pixel will be generated from a Poisson distribution with mean of 5.D) adds "salt and pepper" noise to the image I. The default for V is 0. The result.5 and then scaled back down by 1e12. For example. J = IMNOISE(I. B = MEDFILT2(A. IMFILTER: IMFILTER N-‐D filtering of multidimensional images. ‘salt& pepper'.04.V) adds multiplicative noise to the image I.using the equation J = I + n*I. where D is the noise density. B = IMFILTER(A.5e-‐12. The default HSIZE is [3 3].SIGMA) returns a rotationally symmetric Gaussian lowpass filter of size HSIZE with standard deviation SIGMA (positive).[M N].5.NOISE) filters the image I using pixel-‐wise adaptive Wiener filtering. Mean(A): M = mean(A) returns the mean value along the first array dimension of A whose size does not equal 1. WIENER2 uses a pixel-‐wise adaptive Wiener method based on statistics estimated from a local neighborhood of each pixel. Value Description Average Averaging filter gaussian Gaussian lowpass filter laplacian Approximates the two-‐dimensional Laplacian operator Prewitt Prewitt horizontal edge-‐emphasizing filter Sobel Sobel horizontal edge-‐emphasizing filter Types: Gaussian: Gaussian lowpass filter. The default ALPHA is 0. M and N default to 3. If you omit the [M N] argument. Laplacian: filter approximating the 2-‐D Laplacian operator. FSPECIAL: FSPECIAL Create predefined 2-‐D filters. The parameter ALPHA controls the shape of the Laplacian and must be in the range 0.ALPHA) returns a 3-‐by-‐3 filter approximating the shape of the two-‐dimensional Laplacian operator. J = WIENER2(I.HSIZE. .2. H = FSPECIAL(TYPE) creates a two-‐dimensional filter H of the specified type and returns H as correlation kernel. The additive noise (Gaussian white noise) power is assumed to be NOISE. in which case H is a square matrix. the default SIGMA is 0. HSIZE can be a vector specifying the number of rows and columns in H or a scalar.WIENER2 lowpass filters an intensity image that has been degraded by constant power additive noise.0 to 1. using neighborhoods of size M-‐ by-‐N to estimate the local image mean and standard deviation. H = FSPECIAL('laplacian'.0. H = FSPECIAL('gaussian'. nonvector matrix => mean(A) treats the columns of A as vectors and returns a row vector whose elements are the mean of each column. If A is an empty 0-‐by-‐0 matrix => mean(A) returns NaN. If A is a nonempty. . If A is a multidimensional array => mean(A) treats the values along the first array dimension whose size does not equal 1 as vectors and returns an array of row vectors.If A is a vector => mean(A) returns the mean of the elements. 3). img2=imread('coins. subplot(335). subplot(333). subplot(333). imshow(noi). imshow(noi2). title('speckle noise'). b=imnoise(a.05). noi3=imnoise(img. .'poisson').0. title('Rice').'speckle'. noi4=imnoise(img.0. title('Speckle'). subplot(336).png').07). subplot(331). subplot(334).0.tif'). noi=imnoise(img.'salt & pepper'. title('Gaussian').[3 3]). subplot(332). subplot(331). imshow(img). imshow(b).01).0.b)/255.07). title('Average'). title('original image'). title('Coins'). imshow(a). FILTERING %speckle noise a=imread('cameraman.07.'gaussian'. title('Salt and Pepper').ADDITION OF NOISE img=imread('Rice.'speckle'. subplot(332). noi2=imnoise(img2. imshow(noi3).0. imshow(K). K = filter2(fspecial('average'. L = medfilt2(b. title('Poisson').png'). imshow(noi4). imshow(img2). subplot(337). subplot(334). imshow(L).'poisson'). title('Average'). title('Gaussian'). title('Weiner').5). imshow(L). imshow(a).[3 3]). subplot(331). imshow(c). title('original image'). m = wiener2(c.[5 5]).subplot(334). imshow(n). imshow(m). o=filter2(fspecial('log'.3. subplot(335). imshow(o). n=filter2(fspecial('gaussian'.3.tif').0.3). . subplot(332). subplot(335).[5 5]).0. K = filter2(fspecial('average'. imshow(K). title('poisson noise'). %poisson noise a=imread('cameraman.[5 5].0. subplot(336).b)/255. n=filter2(fspecial('gaussian'. title('Log'). imshow(m).c)/255. subplot(336).b)/255.5). L = medfilt2(c. c=imnoise(a. title('Weiner'). m = wiener2(b. title('Median').c)/255.5). title('Gaussian'). subplot(333). title('Median'). imshow(n). 02). imshow(o). subplot(337). title('Median').0. title('Gaussian'). n=filter2(fspecial('gaussian'.d)/255. imshow(m). title('original image'). imshow(d).5). %gaussian noise a=imread('cameraman.0. L = medfilt2(d. subplot(331).tif').tif'). title('Log'). subplot(334). subplot(332).c)/255. subplot(336). imshow(L). title('salt&pepper noise').[5 5]). title('original image'). subplot(331). title('Average'). m = wiener2(d. subplot(335). K = filter2(fspecial('average'.3.0.0.'salt & pepper'. subplot(333). title('Weiner'). o=filter2(fspecial('log'.d)/255. imshow(n).'gaussian'. e=imnoise(a.[3 3]).01). imshow(a).3). title('Log'). imshow(K).[5 5]. .o=filter2(fspecial('log'. imshow(o).0.[5 5].5). imshow(a).5). subplot(337). d=imnoise(a.001.0. subplot(332).d)/255. %salt&pepper noise a=imread('cameraman. subplot(333).3).e)/255. imshow(n).[3 3]). title('Median'). subplot(335).[5 5]. subplot(337). title('gaussian noise') K = filter2(fspecial('average'.5). subplot(336).[5 5]). m = wiener2(e. o=filter2(fspecial('log'. title('Log'). imshow(o). title('Average').e)/255. title('Weiner'). . imshow(L).0.3. subplot(334). imshow(m). n=filter2(fspecial('gaussian'. title('Gaussian'). L = medfilt2(e.e)/255.0.imshow(e). imshow(K).5). OBSERVATION NOISE FILTERING OF SPECKLE NOISE . FILTERING OF SALT&PEPPER NOISE FILTERING OF POISSON NOISE . FILTERING OF GAUSSIAN NOISE . SE = strel('ball'.EX. RGB2GRAY Converts RGB image or colormap to grayscale. resolution. It displays the info about file size. ‘rgb2gray’ converts RGB images to grayscale by eliminating the hue and saturation information while retaining the luminance STREL Creates a stereo element of desired shape SE = strel(shape. SYNTAXES USED: IMREAD IMSHOW IMDIVIDE IMRESIZE IMFINFO IMFINFO displays information about graphics file.fmt’) returns a structure whose fields contain information about an image in a graphics file. parameters) creates a structuring element. MN) SE = strel('square'. N) SE = strel('diamond'. R) SE = strel('disk'. Depending on shape. a=imfinfo(‘filename. N) SE = strel('line'. See the syntax descriptions that follow for details about creating each type of structuring element.NO: MORPHOLOGICAL OPERATION DATE: AIM: To write a MATLAB program to perform the following morphological operations on the given image: a) Dilation b) Erosion c) Opening & closing SOFTWARE USED: MATLAB Version 2013. image type. LEN. R) SE = strel('rectangle'. W) . R. etc. strel can take additional parameters. This table lists all the supported shapes. R. height. H. SE. of the type specified by shape. DEG) SE = strel('octagon'. width. IM2. . where NHOOD is an array of 0's and 1's that specifies the structuring element neighbourhood.SE) performs morphological closing on the gray scale or binary image IM. The argument SE must be a single structuring element object. The morphological open operation is erosion followed by a dilation. using each structuring element in SE in succession. or array of structuring element objects. IM2 = imopen(IM. IMDILATE IM2 = imdilate(IM.NHOOD) erodes the image IM.If IM is logical and the structuring element is flat. If SE is an array of structuring element objects. imdilate performs multiple dilations of the input image. it performs grayscale dilation. The argument SE is a structuring element object. SE. as opposed to an array of objects. or packed binary image IM. must be a single structuring element object.n) applies the operation n times.operation) applies a specific morphological operation to the binary image BW. IMOPEN IM2 = imopen(IM. binary. n can be Inf. The morphological close operation is a dilation followed by an erosion. returning the eroded imageIM2. returning the dilated image.operation. or packed binary image IM. returned by the strelfunction.BW2 = bwmorph(BW. IM2 = imerode(IM. in which case the operation is repeated until the image no longer changes. as opposed to an array of objects. The structuring element. where NHOOD is an array of 0's and 1's that specifies the structuring element neighbourhood.SE) performs morphological opening on the grayscale or binary image IM with the structuring element SE. The argument SE is a structuring element object or array of structuring. using the same structuring element for both operations. IMCLOSE IM2 = imclose(IM.SE) erodes the grayscale. imdilate performs binary dilation.NHOOD) performs opening with the structuring element strel(NHOOD).SE) dilates the grayscale. IM2. binary.IMERODE IM2 = imerode(IM. otherwise. BWMORPH BW2 = bwmorph(BW. using the same structuring element for both operations. returning the closed image. disp(s2). s3 = strel('line'. d = imdilate(a. subplot(427) imshow(g). title('Dilated image-‐line 3').s4). title('Dilated image-‐line 2'). title('Dilated image-‐diamond').s2).6). EROSION a = imread('coins.5.disp(s5).disp(s6). s5 = strel('disk'.10.png').6. subplot(426) imshow(f). subplot(421). s6 = strel('diamond'.s3). subplot(423) imshow(c).10.disp(s3).8).10.disp(s1). b = imdilate(a.90).0).MORPHOLOGICAL OPERATION DILATION a = imread('cameraman.s6). subplot(424) imshow(d). imshow(a).s5). title('Dilated image-‐line 1'). subplot(425) imshow(e). f= imdilate(a.0).45). e= imdilate(a.s1). s1 = strel('line'. s2 = strel('line'.disp(s1). s1 = strel('line'.disp(s4).tif'). b = imerode(a. . c = imdilate(a. s4 = strel('ball'. title('Original image') subplot(422) imshow(b). title('Dilated image-‐disc').s1). title('Dilated image-‐ball').10. g= imdilate(a.6). s6).disp(s2). subplot(424) imshow(d).45).disp(s3). subplot(423) imshow(c).10. title('Eroded image-‐ball').6). title('Eroded image-‐line 1'). title('Eroded image-‐line 3').disp(s6). . s6 = strel('diamond'.0).5.10. title('Original image') subplot(422) imshow(b). subplot(427) imshow(g). imshow(a).4). s3 = strel('line'. title('Original image') subplot(422) imshow(b). s4 = strel('ball'. CLOSED a = imread('cameraman. s2 = strel('line'. s1 = strel('line'. d = imerode(a. title('Eroded image-‐line 2'). title('Eroded image-‐disc').disp(s4).90).s3).tif'). e= imerode(a.subplot(421).6. imshow(a). subplot(421).disp(s1). subplot(426) imshow(f).s1). title('Eroded image-‐diamond'). f= imerode(a.10.s4). s5 = strel('disk'. c = imerode(a. g= imerode(a.s5). subplot(425) imshow(e).disp(s5).8).s2). b = imclose(a. s5 = strel('disk'.disp(s5). subplot(423) imshow(c).s2). s4 = strel('ball'. subplot(424) imshow(d).disp(s1). s2 = strel('line'. c = imclose(a.45).10.disp(s2). e= imclose(a.s2). title('Closed image-‐line 3'). s3 = strel('line'. g= imclose(a.disp(s2).tif'). subplot(426) imshow(f).disp(s4).10.4). subplot(423) imshow(c).5. title('Closed image-‐diamond').10.disp(s6). s2 = strel('line'. c = imopen(a. title('Closed image-‐disc'). title('Opened image-‐line 1'). s1 = strel('line'.6. s6 = strel('diamond'. d = imclose(a.s4).title('Closed image-‐line 1'). subplot(427) imshow(g). title('Original image') subplot(422) imshow(b).s1).0). f= imclose(a.s6).disp(s3). title('Closed image-‐ball').8).s5). subplot(421). b = imopen(a.s3). subplot(425) imshow(e).6).90). title('Closed image-‐line 2'). OPENED a = imread('cameraman. .10.90). imshow(a). f= imopen(a. s6 = strel('diamond'.disp(s4). s4 = strel('ball'.6).45). e= imopen(a. subplot(426) imshow(f).4).s6). subplot(427) imshow(g). d = imopen(a. subplot(424) imshow(d).10.disp(s3). title('Opened image-‐line 3').8).5.6. s5 = strel('disk'. subplot(425) imshow(e).title('Opened image-‐line 2').s5). title('Opened image-‐disc'). .disp(s5).disp(s6). title('Opened image-‐diamond').s3). title('Opened image-‐ball').s4). s3 = strel('line'. g= imopen(a. OBSERVATION DILATED ERODED . CLOSED OPENED . THEORY: Thresholding: A special case of contrast stretching where α=γ=0is called clipping.EX.NO: GRAY LEVEL ENHANCEMENT DATE: AIM: To write a MATLAB program to perform the following enhancements on an image: a) Brightness and Contrast Adjustment b) Gamma Transformation/ Power Law Transformation c) Gray Level Slicing d) Bit Plane Slicing e) Logarithmic transformation f) Contrast stretching SOFTWARE USED: MATLAB Version 2013. Thresholding is a special case of clipping where a=b=t and the output becomes binary. . The figure shows atypical contrast stretching transformation. Fig(a)) The second approach is to brighten the desired range of gray levels but preserve the background and gray-‐level tonalities in the image.(Fig(b)) . 0≤u<a β( u-‐a) + Va . For dark region α>1. a≤u<b γ( u-‐b) + Vb . b≈ 2L/3 Bright region stretch γ>1 Gray level slicing: Highlighting a specific range of gray levels in an image. There are two basic themes for gray level slicing. which can be expressed as: V={ αu . a & b parameters can be obtained by examining histogram. b≤u<L The slope of the transformation is chosen greater than unity in the region of stretch.Contrast stretching: Low contrast images occur often due to poor or non-‐uniform lightning conditions or due to non-‐linearity or small dynamic range of the imaging sensor. One approach is to display a high value for all the gray levels in the range of interest and a low value for all other gray levels (Binary image. a≈ L/3 Midstretch region β>1. Mapping all pixels between 0 to 127 to one level & 128-‐255 to another gray level.Bit plane slicing: Highlighting the contribution made to the total image appearance by specific bits might be perceived. when separated into bit planes ranging from 0 to 7. . the 0th plane represents least significant bit to bit plane 7th the most significant bit. Each pixel representation by 8 bits. 0-‐plane : lower order bits in bytes 7-‐plane: higher order bits Separating bit planes is useful for analyzing relative importance played by each bit. The higher order bits contain majority of visually significant data. The opposite is true for higher levels of input levels. The opposite is true for inverse log transformation. We would use a transformation of this type to expand the values of dark pixels in an image while compressing the higher level values. . Log transformations: The general form of the log transformation is s = c log(1+r) c: constant The shape of the log curve shows that this transformation maps a narrow range of low gray level values in the input image into a wider range of output levels. : positive constants Power law curves with the fractional values of γ map a narrow range of dark input values into a wider range of output values. with the opposite being true for higher values of input levels. . Power law transformations: The basic form of power law transformation is s = cr γ C. . STRETCHLIM STRETCHLIM Find limits to contrast stretch an image. BITGET BITGET Get bit. .BIT) returns the value of the bit at position BIT in A. J = IMADJUST(I) maps the values in intensity image I to new values in J such that 1% of data is saturated at low and high intensities of I. 32 for UINT32s.g. A must be an unsigned integer or an array of unsigned integers..7 1]. LOW_HIGH = STRETCHLIM(I.6 .2 .3 0. This increases the contrast of the output image J. SYNTAXES USED: IMREAD IMSHOW IMRESIZE IMFINFO RGB2GRAY IMADD IMADJUST IMADJUST Adjust image intensity values or colormap.[. RGB2 = imadjust(RGB1.TOL) returns a pair of gray values that can be used by IMADJUST to increase the contrast of an image.[]). C = BITGET(A. and BIT must be a number between 1 and the number of bits in the unsigned integer class of A e. con1=input('Enter Constant above 1='). img=imread('pout. [I.*log10(1+f).*log10(1+f). .j)). for i=1:I for j=1:J f=double(img(i. clear.J]=size(img). title('Original'). imshow(img). title('Log Transformed above 1'). subplot(221). dou=im2double(img). img=imread('Cameraman. z(i. end end subplot(223). end end subplot(222).tif'). imshow(img).GRAY LEVEL ENHANCEMENT LOG TRANSFORM clc.j)=con1. imshow(z1).j)=con.tif'). GAMMA TRANSFORM clc. title('Log Transformed below 1'). for i=1:I for j=1:J f=double(img(i. con=input('Enter Constant below 1='). imshow(z). con=input('Enter the Constant '). title('Original Image'). subplot(221). g=input('Enter Gamma Value above 1 '). clear. z1(i.J]=size(img).j)). [I. title('Above 1').J]=size(img).j))^g. imshow(e).j)=20. else img (i. imshow(img). imshow(f). title('Below 1'). GRAY SLICING clear.y]=size(img). subplot(221).png'). [I. imshow(img).j)<=210 img (i. g1=input('Enter Gamma Value below 1 '). .[x.j)=250. end end end subplot(222). title('Original'). title('Gray Sliced'). end end subplot(222). end end subplot(223).j)=con*(dou(i.j)>=150 && img(i. for i=1:I for j=1:J if img(i. clc.j))^g1.j)=con*(dou(i. for i=1:x for j=1:y f(i. img=imread('Rice. for i=1:x for j=1:y e(i. subplot(3. imshow(img).i). subplot(322).i).tif'). for i=1:8 b=bitget(im. imshow(adj). subplot(323). title('Original Image'). adj=imadjust(img.[]).stretchlim(img).png'). subplot(325). imhist(img).png'). subplot(324).J]=size(im).BIT SLICING clear. imshow(b. im=imread('cameraman.3. clc. subplot(321). title('Enhanced Image'). imhist(adj). [I. title('Contrast Image'). end CONTRAST ENHANCEMENT img=imread('Rice. .[]). img2=imread('Rice. imcontrast(gca). imshow(img2). OBSERVATION: LOG TRANSFORM GAMMA TRANSFORM . BIT SLICING GRAY SLICING . CONTRAST ENHANCEMENT . Edge detection is difficult in noisy images. or diagonal edges. Sobel b. which is constructed to be sensitive to large gradients in the image while returning values of zero in uniform regions. One kernel is simply the other rotated by 90°. Attempts to reduce the noise result in blurred and distorted edges. The discontinuities are abrupt changes in pixel intensity which characterize boundaries of objects in a scene. Prewitt SOFTWARE USED: MATLAB Version 2013 THEORY Edge detection refers to the process of identifying and locating sharp discontinuities in an image. Roberts d.EX. since both the noise and the edges contain high frequency content. The various operators used may be as follows: SOBEL The operator consists of a pair of 3×3 convolution kernels as shown in Figure 1.NO: EDGE DETECTION DATE: AIM: To write a MATLAB program to perform the detection of edges by following algorithms: a. Operators can be optimized to look for horizontal. Canny c. . The geometry of the operator determines a characteristic direction in which it is most sensitive to edges. Classical methods of edge detection involve convolving the image with an operator (a 2-‐D filter). vertical. The Sobel operator performs a 2-‐D spatial gradient measurement on an image. depending on what the value of the gradient in the y-‐direction is equal to.The magnitude. Whenever the gradient in the x direction is equal to zero. The gradient magnitude is given by: Typically. or edge strength. If GY has avalue of zero. The angle of orientation of the edge (relative to the pixel grid) giving rise to the spatial gradient is given by: q = arctan(Gy /Gx) CANNY In order to implement the canny edge detector algorithm. These can then be combined together to find the absolute magnitude of the gradient at each point and the orientation of that gradient. the edge direction has to be equal to 90 degrees or 0 degrees. of the gradient is then approximated using the formula The direction of the edge is computed using the gradient in the x and y directions. an approximate magnitude is computed using: which is much faster to compute. The Gaussian smoothing can be performed using standard convolution methods.These kernels are designed to respond maximally to edges running vertically and horizontally relative to the pixel grid. Otherwise the edge direction will equal 90 degrees. an error will be generated when sumX is equal to zero. The kernels can be applied separately to the input image. the approximate absolute gradient magnitude (edge strength) at each point can be found. Then. the next step is to find the edge strength by taking the Gradient of the image. one kernel for each of the two perpendicular orientations. it is first necessary to filter out any noise in the original image before trying to locate and detect any edges. the edge direction will equal 0 degrees. Theformula for finding the edge direction is just: Theta = invtan (Gy / Gx) . to produce separate measurements of the gradient component in each orientation (call these Gx and Gy). After smoothing the image and eliminating the noise. However. If a single threshold. hysteresis uses 2 thresholds. Non-‐maximum suppression is used to trace along the edge in the edge direction and suppress any pixel value (sets it equal to 0) that is not considered to be an edge. Then. T1 isapplied to an image. and an edge has an average strength equal to T1. then due to noise. This is very similar to the Sobel operator. After the edge directions are known. ROBERTS The Roberts Cross operator performs a simple. Any pixel in the image that has a value greater than T1 is presumed to be an edge pixel. and is marked as such immediately. Streaking is the breaking up of an edge contour caused by the operator output fluctuating above and below the threshold. any pixels that are connected to this edge pixel and that have a value greater than T2 are also selected as edge pixels. If you think of following an edge. non-‐maximum suppression now has to be applied. Pixel values at each point in the output represent the estimated absolute magnitude of the spatial gradient of the input image at that point. a high and a low. This will give a thin line in the output image. The operator consists of a pair of 2×2 convolution kernels as shown in One kernel is simply the other rotated by 90. To avoid this. you need a gradient of T2 to start but you don't stop till you hit a gradient below T1. there will be instances where the edge dips below the threshold. Equally it will also extend above the threshold making an edge look like a dashed line. Finally. . hysteresis is used as a means of eliminating streaking. 2-‐D spatial gradient measurement on an image. quick to compute. PREWITT Prewitt operator is similar to the Sobel operator and is used for detecting vertical and horizontal edges inimages. SYNTAXES USED: IMREAD IMSHOW SOBEL METHOD BW = edge(I, ‘sobel') specifies the Sobel method.The Sobel method finds edges using the Sobel approximation to the derivative. It returns edges at those points where the gradient of I is maximum. PREWITT METHOD BW = edge(I,'prewitt') specifies the Prewitt method. The Prewitt method finds edges using the Prewitt approximation to the derivative. It returns edges at those points where the gradient of I is maximum. ROBERTS METHOD BW = edge(I,'roberts') specifies the Roberts method. The Roberts method finds edges using the Roberts approximation to the derivative. It returns edges at those points where the gradient of I is maximum. CANNY METHOD BW = edge(I,'canny') specifies the Canny method. The Canny method finds edges by looking for local maxima of the gradient of I. The gradient is calculated using the derivative of a Gaussian filter. The method uses two 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 DETECTION img1=imread('cameraman.tif'); img2=edge(img1,'canny'); img3=edge(img1,'log'); img4=edge(img1,'prewitt'); img5=edge(img1,'roberts'); img6=edge(img1,'sobel'); img7=edge(img1,'zerocross'); subplot(421); imshow(img1); title('original'); subplot(422); imshow(img2); title('canny'); subplot(423); imshow(img3); title('log'); subplot(424); imshow(img4); title('prewitt'); subplot(425); imshow(img5); title('roberts'); subplot(426); imshow(img6); title('sobel'); subplot(427); imshow(img7); title('zerocross'); OUTPUT: EDGE DETECTION NO: DISCRETE FOURIER TRANSFORMATION DATE: AIM: To write a MATLAB program to a) To generate the DFT basis image for the given matrix dimension b) Find the Discrete Fourier Transform of an image.l) is obtained by multiplying the spatial image with the corresponding base function and summing the result. The equation can be interpreted as: the value of each point F(k.b) is the image in the spatial domain and the exponential term is the basis function corresponding to each point F(k.EX. but only a set of samples which is large enough to fully describe the spatial domain image.e. . The output of the transformation represents the image in Fourier as ‘Frequency domain’ while the input image is the spatial domain equivalent. For a square image of size N×N. Discrete Fourier transform The DFT is the sampled Fourier Transform and therefore does not contain all frequencies forming an image. c) To prove the rotational property & convolution of DFT SOFTWARE USED: MATLAB version 2013 THEORY Fourier Transform The Fourier transform is an important image processing tool which is used to decompose an image into its sine and cosine components. i.l) in the Fourier space. the image in the spatial and Fourier domain is of the same size. The number of frequencies corresponds to the number of pixels in the spatial domain image. the two-‐dimensional DFT is given by: where f(a. F(0. a double sum has to be calculated for each image point. The Fourier Transform produces a complex number valued output image which can be displayed with two images.e. often only the magnitude of the Fourier Transform is displayed. again using None-‐dimensional Fourier Transforms. However. either with the real and imaginary part or with magnitude and phase. it can be written as where Using these two formulas. In image processing. .0) represents the DC-‐component of the image which corresponds to the average brightness and F(N-‐1.The basis functions are sine and cosine waves with increasing frequencies. However. because the Fourier Transform is separable. The inverse Fourier transform is given by: Note the normalization term in the inverse transformation. we must make sure to preserve both magnitude and phase of the Fourier image. but it should not be used for both. This normalization is sometimes applied to the forward transform instead of the inverse transform. Expressing the two-‐dimensional Fourier Transform in terms of a series of 2N one-‐dimensional transforms decreases the number of required computations.N-‐1) represents the highest frequency. the spatial domain image is first transformed into an intermediate image using N one-‐dimensional Fourier Transforms. This intermediate image is then transformed into the final image. as it contains most of the information of the geometric structure of the spatial domain image. To obtain the result for the above equations. i. if we want to re-‐transform the Fourier image into the correct spatial domain after some processing in the frequency domain. 1).:. For example. The result is m-‐by-‐n. then fft2 computes the DFT of X(:. its transpose and input vector Convolution Property Step 1 Generate a binary image using 0’s and 1’s Step 2 Two images are generated Step 3 Convolve both the generated images Step 4 Take the FFT of the two images separately.3).2) and X(:. n) or B = zeros([m n]) returns an m-‐by-‐n matrix of zeros.SYNTAXES USED: IMREAD IMSHOW ZEROS () creates an array of all zeros. if size(X) = [100 100 3].n) truncates X. ALGORITHM Step 1 Define an input vector i Step 2 Form the Dft matrix function Step 3 Multiply the Dft matrix. and fftn by moving the zero-‐frequency component to the center of the array. Y = fftshift(X) rearranges the outputs of fft.:. or pads X with zeros to create an m-‐by-‐n array before doing the transform.:. is the same size as X.Y = fft2(X. If the dimensionality of X is greater than 2. B = zeros (m. rotated image & their corresponding FFT’s . multiply and take the inverse Fourier transform Step 5 Plot the convoluted and multiplied output Step 6 Verify if the images are equal Rotation property Step 1 Generate a binary image using 0’s & 1’s Step 2 Rotate the generated image using function imrotate() Step 3 Take the magnitude of the FFT of the original and rotated image Step 4 Display the image. X(:. FFTSHIFT() Shift zero-‐frequency component to center of spectrum. Y = fft2(X) returns the two-‐dimensional discrete Fourier transform (DFT) of X. The DFT is computed with a fast Fourier transform (FFT) algorithm. the fft2 function returns the 2-‐D DFT for each higher dimensional slice of X. fft2. It is useful for visualizing a Fourier transform with the zero-‐frequency component in the middle of the spectrum. The result. m . FFT2(X) returns the two-‐dimensional discrete Fourier transform (DFT) of X. Y. t=1. subplot(232). imshow(mag{i. end end end end subplot(221).t). title('FFT'). for i=1:N for j=1:M subplot (M. title('IFFT'). clc. subplot(234). t=t+1. d=ifft2(c). imshow(a). subplot(231). N=M. title('Original').png').q+1)=(exp((-‐2*pi*i*k*n)/N))*(exp((-‐2*pi*i*p*q)/M)). c=fft2(b). end end DFT AND IDFT TO IMAGE: a=imread('Coins. imshow(c). subplot(233). . mag=abs(c). for k=0:N-‐1 for p=0:N-‐1 for n=0:N-‐1 for q=0:N-‐1 g{k+1.j}). b=im2double(a).N.DISCRETE FOURIER TRANSFORM DFT clear. mag=g. i=sqrt(-‐1).p+1}(n+1. imshow(d). M=input('Enter M='). ff3=ff1. ff1=fft2(img1). subplot(236). TO PROVE CONVOLUTION PROPERTY: img1=zeros(256). subplot(234).imshow(mag).title('Image 1').'same'). imshow(ang). subplot(235). subplot(231). subplot(235).imshow(ff2).title('Convolution in Time Domain'). b=fft2(a1). subplot(233). end end img2=ones(256). subplot(232). ang=angle(c).imshow(img3).title('Multiplication in Frequency Domain'). for i=90:170 for j=90:170 img1(i. img4=fftshift(ifft2(ff3)).title('Image 2'). TO PROVE ROTATION PROPERTY: clc.imshow(img4). title('Image'). imshow(a).imshow(ff1). subplot(231). title('Magnitude Plot'). title('Phase Plot'). .png'). for i=40:210 for j=40:210 img2(i. end end img3=conv2(img1. a1=im2double(a).imshow(img2). clear. ff2=fft2(img2).imshow(img1).title('FFT of Image 1').*ff2. a=imread('coins.j)=1.title('FFT of Image 2').j)=0.img2. title('FFT of Image').90). imshow(d). title('Rotated Image'). title('FFT of Rotated Image'). subplot(233). .subplot(232). imshow(c). subplot(234). c=imrotate(a1. imshow(b). d=fft2(c). DISCRETE FOURIER TRANSFORM GENERATED IMAGES DFT & IDFT IN IMAGE: . TO PROVE CONVOLUTION PROPERTY: TO PROVE ROTATION PROPERTY: . EX.NO: DISCRETE COSINE TRANSFORMATION DATE: AIM: To write a MATLAB program a) To generate a Basis images with the given matrix dimension using DCT transforms b) To perform the discrete cosine transform on the given image SOFTWARE USED: MATLAB Version 2013 THEORY The NxN Cosine transform matrix also called Discrete Cosine transform ( DCT ) is defined as The 2-‐D DCT of a sequence & The inverse discrete transform are defined as : . If Y is a matrix.SYNTAXES USED: IMREAD IMSHOW SUBPLOT: subplot Create axes in tiled positions.N) pads or truncates the vector Y to length N before transforming. ALGORITHM : Basis function generation Step 1 Open a new M file Step 2 Get the input matrix dimension .Complex results are produced if X is not positive. N) pads or truncates the vector X to length N before transforming. Y = dct(X. LOG: Natural logarithm. ABS: Absolute value. the idct operation is applied to each column. abs(X) is the absolute value of the elements of X.N Step 3 Assign the values for α(k) α(l) Step 4 Use the suitable Matlab expression for cosine transforms inside the loop Step 5 Repeat the loop till N-‐1 Step 6 Plot the basis vectors as NxN DCT of an image Step 1 Read the input image in a variable a Step 2 Convert it to grayscale Step 3 Resize the image to NxN size Step 4 Generate the CT transform matrix of size N Step 5 Apply the rule U=A. returning the original vector if Y was obtained using Y = DCT(X). X = idct(Y.AT and store the size N Step 6 Convert the output image in absolute and logarithmic form Step 7 Plot the DCT of an image . The vector Y is the same size as X and contains the discrete cosine transforms coefficients. Y = dct(X) returns the discrete cosine transform of X. DCT: Discrete cosine transform. When X is complex. IDCT: Inverse discrete cosine transform.V. X = idct(Y) inverts the DCT transform. abs(X) is the complex modulus (magnitude) of the elements of X. log(X) is the natural logarithm of the elements of X. img4=idct2(img3). for i=1:N for j=1:M subplot(N. mag=abs(img3).imshow(img4). end end end end mag=h.N)*sqrt(2/M).imshow(img3). N=input('Enter Order=').imshow(mag). a2(1)=sqrt(1/M). k=1.*pi)/(2. subplot(231).N)*sqrt(2/N). imshow(mag{i.imshow(img).v+1}(x+1.*v .*N)).*x)+1).png').M. subplot(234). close all. subplot(233).DISCRETE COSINE TRANSFORM clc. pha=angle(img3).*N)). end end DCT & IDCT IN IMAGE: clear.title('DCT'). for u=0:N-‐1 for v=0:M-‐1 for x=0:N-‐1 for y=0:M-‐1 h{u+1. . img=imread('Rice. a1=ones(1. clc. subplot(232). img2=im2double(img).imshow(pha). k=k+1.k). subplot(235).title('IDCT').j}).title('Magnitude Plot').*pi)/(2. M=N.title('Phase Plot').y+1)=a1(u+1)*a2(v+1)*cos((((2.*cos((((2.title('Original'). clear. a2=ones(1. a1(1)=sqrt(1/N).*y)+1).*u. img3=dct2(img2). OUTPUT: DISCRETE COSINE TRANSFORM GENERATED IMAGES DCT & IDCT IN IMAGE: EX NO. HISTOGRAM EQUALISATION DATE AIM To write a MATLAB code to enhance contrast the given images using histogram equalization SOFTWARE USED MATLAB 2013a THEORY Histogram Histogram of a digital image with intensity levels in the range [0,L-‐1] is a discrete function h(rk) = nk Where rk = kthintensity value in interval (0,G) nk = number of pixels in the image with intensity rk It is a graphical representation of showing a visual impression of distribution of data. It is the estimate of probability distribution of a continuous variable. The normalized Histogram is obtained by dividing all elements of h(rk) by total number of pixels in image P(rk) = h(rk)/ n = nk/ n Histogram equalization It is a grey level mapping process that seeks to produce monochrome images with uniform intensity histograms. It gives the net result of this intensity level with increased dynamic range, which tends to have high contrast. The transformation is the cumulative distribution function SYNTAXES USED IMREAD IMSHOW IMHIST(I) calculates the histogram for the intensity image I and displays a plot of the histogram. The number of bins in the histogram is determined by the image type. If I is a grayscale image, imhist uses a default value of 256 bins. If I is a binary image, imhist uses two bins. imhist(i,n) displays a histogram for the intensity image I, where n specifies the number of bins used in the histogram. n also specifies the length of the colorbar displayed at the bottom of the histogram plot. If I is a binary image, n can only have the value 2. HISTEQ Histeq enhances the contrast of images by transforming the values in an intensity image, or the values in the colormap of an indexed image, so that the histogram of the output image approximately matches a specified histogram. J = histeq(I,hgram) transforms the intensity image I so that the histogram of the output intensity image J with length(hgram) bins approximately matches hgram. The vector hgram should contain integer counts for equally spaced bins with intensity values in the appropriate range: [0, 1] for images of class double, [0, 255] for images of class uint8, and [0, 65535] for images of class uint16. histeq automatically scales hgram so that sum(hgram) = prod(size(I)). The histogram of J will better match hgram when length(hgram) is much smaller than the number of discrete levels in I. J = histeq(I,n) transforms the intensity image I, returning in J an intensity image with n discrete gray levels. A roughly equal number of pixels is mapped to each of the n levels in J, so that the histogram of J is approximately flat. (The histogram of J is flatter when n is much smaller than the number of discrete levels in I.) The default value for n is 64. ALGORITHM The following steps are preformed to obtain Histogram Equalisation. Find the frequency of each pixel value of bins = 5 Pixel value 1 occurs 3 times Pixel value 2 occurs 3 times and so on Find the probability of each frequency The probability of pixel value 1’s = Frequency (1)/No of pixels =3/9 Find the cumulative histogram of each pixel The cumulative histogram of 1 = 3 The cumulative histogram of 2 = cumulative histogram of 1 + Frequency of 2 = 3 + 2 = 5 Find the cumulative probability distribution of each pixel CDF of 1 = Cumulative histogram of 1 / No of pixels = 3/9 Calculate the final value of each pixel by multiplying of with no of bins CDF of 1 = 3/9 * 5 = 1.6667. Round off ~ 2 Replace the final values .Step 1 Step 2 Step 3 Step 4 Step 5 Step 6 Step 7 Step 8 Consider a matrix A Let No. new= new + 1. end new = round(cdf * maximum_value). end end end for n=1:row for m=1:col t = I(n.m).1).q).q).m) == 0 I(n.HISTOGRAM EQUALIZATION WITHOUT USING INBUILT FUNCTION clear. subplot(2. for n=1:row for m=1:col if I(n. title(' Image1').2. end end b=b-‐1. h(t) = h(t) + 1.tif'). t=b(p. cdf(1) = pdf(1). z=zeros(1. I=imread('cameraman. maximum_value=max((max(I))). I=double(I). for p=1:row for q=1:col temp=I(p.m)=1. imshow(uint8(I)) . [row col]=size(I).q)=new(temp). h=zeros(1. for x=2:maximum_value cdf(x) = pdf(x) + cdf(x-‐1). b(p. c=row*col.300). clc.300). . end end pdf = h/c. z(t)=z(t)+1. tif').title('Original Image Histogram').2.4).2.imhist(equalised). title('Image2').title('Equalised Image Histogram'). subplot(2.imshow(equalised).title('Original Image'). subplot(222). bar(z) . HISTOGRAM EQUALIZATION USING INBUILT FUNCTION img1=imread('cameraman. equalised=histeq(img1). title('Histogram Equalisation of image2'). subplot(2.2). .2. subplot(223). imshow(uint8(b)) .imshow(img1). subplot(221).imhist(img1).3). title('Histogram of the Original Image').title('Equalised Image').subplot(2. subplot(224). bar(h) . OUTPUT HISTOGRAM EQUALIZATION WITHOUT INBUILT FUNCTION HISTOGRAM EQUALIZATION WITH INBUILT FUNCTION . y)↔ H(u.: IMAGE FILTERING-‐FREQUENCY DOMAIN DATE: AIM: To write a MATLAB program to apply the following filters to the given image: a) 2-‐D Butterworth low pass filter b) 2-‐D Butterworth high pass filter c) Gaussian low pass filter d) Gaussian high pass filter e) Ideal low pass filter f) Ideal high pass filter SOFTWARES USED : MATLAB Version 2013a THEORY: The foundation for linear filtering in frequency domain is the convolution theorem.v) is the filter transfer function The idea in frequency domain filtering is to select a filter transfer function that modifies F(u.EX NO.v) in a specific manner. .y)*h(x.v)F(u.v) where H(u. f(x. v) to the center of the frequency rectangle [ 1 ] D(u. v) = e− D (u . v) = ⎨ ⎩0 if D(u. Display the images and transfer function in 3-‐D view. v) = 2n 1 + [D(u.v) is the transfer function of a lowpass filter. . v) / D0 ] A Gaussian lowpass filter has transfer function given by 2 2 H (u. Step 3 Define the transfer function of the filter and form the transfer matrix. Step 2 Take the Fourier Transform of the image using function fft2(). we see that an ideal filter cuts off all components of F(u.LOWPASS FREQUENCY DOMAIN FILTERS: The transfer function of an ideal lowpass filter is ⎧1 if D(u.v) ALGORITHM: Step 1 Read the image to be filtered.v) outside the circle and keeps all the components on or inside the circle unchanged. Because filter H(u.v) : the distance from point (u. Step 4 Multiply the formed transfer matrix with transformed image. with cut off frequency at distance D0 from the center of the filter. has the transfer function 1 H (u. A Butterworth lowpass filter of order n. Hhp(u. Step 5 Take inverse Fourier transform to get the filtered image.v)=1-‐ Hlp(u.v)= D0 is a circle.v) is given by.v) multiplies the Fourier transform of an image.v ) / 2 D0 Where σ is the standard deviation HIGH PASS FREQUENCY DOMAIN FILTERS: The high pass filtering sharpens the image by attenuating low frequencies and leaving the high frequencies of an image unaltered. then the transfer function of the corresponding high pass filter Hhp(u. v) = (u − M / 2) 2 + (v − N / 2) 2 2 D0 is a positive number The locus of points for which D(u. v) > D0 where D(u. If Hlp(u. v) ≤ D0 H (u. Step 5 Take the inverse Fourier transform using the function ifft2() to get filtered image. mask and fftshift of the mask . Step 2 Create the mask for low pass or high pass filtering. Step 6 Display the filtered image. Step 3 Take the Fourier transform of the mask and of the image using function fft2().Ideal low pass and high pass filter: Step 1 Read the image. Step 4 Multiply the transformed mask and image. png'). imshow(h).FREQUENCY DOMAIN FILTERS BUTTERWORTH LOWPASS FILTER clear. title('LPF as Image').j)=sqrt((i-‐x). x=ceil(X/2).^2). [X. BUTTERWORTH HIGH PASS FILTER clear.^(2*N)).Y]=size(img). fin=ifft2(fil). surf(h). . h(i. subplot(221). y=ceil(Y/2).^2+(j-‐y). [X. fil=h. title('After LPF'). clc. clc.Y]=size(img). subplot(223).j)=1/(1+((d(i.j))/rad). y=ceil(Y/2). N=input('Order of Filter='). imshow(img). imshow(fin1). subplot(222). rad=26. subplot(224). img=imread('Coins. for i=1:X for j=1:Y d(i.*fft1. title('Original'). img=imread('Coins. x=ceil(X/2). title('LPF in 3D'). end end fft1=fftshift(fft2(img)). fin1=uint8(fin). N=input('Order of Filter=').png'). rad=26. subplot(221). imshow(fin1). subplot(224). h(i. else h(i. x=ceil(X/2).^2).*fft1.j)=0. title('Original').png'). img=imread('Coins. title('HPF in 3D'). for i=1:X for j=1:Y d(i. clc. for i=1:X for j=1:Y d(i.j)=1.^2+(j-‐y). end end fft1=fftshift(fft2(img)).^2+(j-‐y). imshow(img).j)=sqrt((i-‐x).^(2*N))). subplot(222). N=input('Order of Filter='). [X.j))/rad). if d(i. fin=ifft2(fil).j)=1-‐(1/(1+((d(i. subplot(223). end . fil=h.j)=sqrt((i-‐x).Y]=size(img). title('After HPF').j)<=rad h(i.^2). title('HPF as Image'). surf(h). y=ceil(Y/2).rad=26. imshow(h). fin1=uint8(fin). IDEAL LOW PASS FILTER clear. *fft1. title('Ideal LPF as Image'). rad=26.j)=1. x=ceil(X/2).j)<=rad h(i. for i=1:X for j=1:Y d(i. fil=h. IDEAL HIGH PASS FILTER clear.png').^2+(j-‐y).Y]=size(img). y=ceil(Y/2). if d(i. imshow(h). subplot(222). fin1=uint8(fin). else h(i. [X. imshow(fin1).*fft1. fin=ifft2(fil). subplot(224). end end end fft1=fftshift(fft2(img)). . fil=h. title('Ideal LPF in 3D').j)=sqrt((i-‐x). title('Original'). subplot(221). end end fft1=fftshift(fft2(img)). title('After Ideal LPF'). surf(h). img=imread('Coins. imshow(img).^2). clc. fin=ifft2(fil).j)=0. subplot(223). N=input('Order of Filter='). title('Ideal HPF as Image'). subplot(221). N=input('Order of Filter='). title('After Ideal HPF').^2))).^2)/(2*((rad). fin=ifft2(fil). subplot(223).j)=exp(-‐(d(i. surf(h). imshow(fin1). GAUSSIAN LOW PASS FILTER: clear. imshow(fin1). clc.png'). subplot(221). title('Original'). subplot(223).fin1=uint8(fin). rad=26. imshow(h). surf(h).^2+(j-‐y). [X. for i=1:X for j=1:Y d(i.Y]=size(img). title('Ideal HPF in 3D'). subplot(224). y=ceil(Y/2). imshow(img). title('Original'). subplot(222). fin1=uint8(fin). img=imread('Coins. fil=h. end end fft1=fftshift(fft2(img)). h(i. imshow(img).j). title('After Gaussian LPF'). x=ceil(X/2). .*fft1. subplot(222).j)=sqrt((i-‐x).^2). ^2+(j-‐y). imshow(img). .png'). subplot(224).j)=sqrt((i-‐x). subplot(223).title('Gaussian LPF in 3D'). surf(h). fil=h. fin=ifft2(fil). imshow(fin1). h(i. title('Gaussian LPF as Image'). title('Gaussian HPF in 3D'). for i=1:X for j=1:Y d(i. imshow(h). subplot(221). fin1=uint8(fin). title('Gaussian HPF as Image'). img=imread('Coins. subplot(224). GAUSSIAN HIGH PASS FILTER: clear.^2). [X. end end fft1=fftshift(fft2(img)).*fft1. y=ceil(Y/2). N=input('Order of Filter=').j)=1-‐exp(-‐(d(i. rad=26.^2)/(2*((rad). subplot(222).Y]=size(img). clc. x=ceil(X/2).j). title('Original'). imshow(h). title('After Gaussian HPF').^2))). OUTPUT: BUTTERWORTH LOWPASS FILTER BUTTERWORTH HIGHPASS FILTER . IDEAL LOWPASS FILTER IDEAL HIGHPASS FILTER . GAUSSIAN LOWPASS FILTER GAUSSIAN LOWPASS FILTER . magenta and yellow are at the other three corners. cmunique.8 nm green : 546. S. Cyan . B and H. G. Human eyes: Primary colors for standardization blue : 435. and B colors perceived by human eyes cover a range of spectrum RGB Colour models: The model is based on a Cartesian co-‐ordinate system. cmpermute. G. rgbplot commands THEORY: Colour image processing deals with colour descriptions of images that are natural and intuitive to humans.1 nm red : 700 nm Cones in human eyes are divided into three sensing categories 65% are sensitive to red light 33% sensitive to green light 2% sensitive to blue (but most sensitive) The R. . EX NO. RGB values are at 3 corners. V components b) Convert the given RGB image to different forms c) Perform colour manipulation using brighten.: COLOUR IMAGE PROCESSING-‐I DATE: AIM: To write a MATLAB program to: a) Display a colour image and its R. Black is at the origin and white is at the corner furthest from the origin. luminance information is stored as a single component (Y). In the NTSC color space. NTSC Colour space: One of the main advantages of this format is that grayscale information is separated from color data. image data consists of three components: luminance (Y).797 -‐74. YCbCr The YCbCr color space is widely used for digital video.214 B HSV colour space: . and chrominance information is stored as two color-‐difference components (Cb and Cr). so the same signal can be used for both color and black and white television sets.000 + G Cr 128 112. Cb represents the difference between the blue component and a reference value. Cr represents the difference between the red component and a reference value. luminance.203 112. and saturation (Q). The first component. represents grayscale information. In this format. Y 16 65.966 R Cb = 128 + -‐37.553 24. while the last two components make up chrominance (color information).481 128.786 -‐18.000 -‐93. hue (I). Hence. saturation and brightness. muddy black is produced. Hue: expressed as an angle around a colour hexagon. As we move along the vertical (gray) axis. as: C 1 R M = 1 -‐ G Y 1 B In theory. giving rise to CMYK model.Hue. typicallyusing the red axis as reference (0◦) axis. It requires CMY data input or an RGB→CMY conversion to be performed internally. V=0 → end of axis is black V=1 →end of axis is white Saturation: (purity of colour) measured as the distance from V axis. Conversion from RGB -‐HSV entails developing the equation to map RGBvalues (which are in Cartesian co-‐ ordinates) to cylindrical co-‐ordinates. value is formulated by looking at RGB colour cube along its gray scale axis(the axis joining the black and white vertices) which results in a hexagonally shaped colour space. . CMY & CMYK colour spaces Cyan. equal amounts of cyan.However. Value: measured along the axis of the cone. size of hexagonal plane perpendicular to the axis changes. saturation. The HSV colour system is based on cylindrical co-‐ordinates. a fourth colour black is added. It is used in colour printers and copiers that deposit colour pigments on paper. practically. magenta and yellow should produce black. Magenta and Yellow are the secondary colours of RGB or alternativelyprimary colours of pigments. HSI colour space: Hue. Converting colours from RGB→HIS Given a colour as R. The angle from the red axis gives the hue. The intensity of all colours in any of these planes is given by the position of the plane on the vertical intensity axis. and B its H. and the length ofthe vector is the saturation. Brightness: subjective descriptor that is impossible to measure. G. and I values are calculated as follows: if B ≤ G ⎧θ H = ⎨ ⎩360 − θ if B > G ⎧⎪ 1 ⎫⎪ 2 [(R − G ) + (R − B )] θ = cos −1 ⎨ 1 ⎬ ⎪⎩ (R − G )2 + (R − B )(G − B ) 2 ⎪⎭ [ ] . S. The dotis an arbitrary colour point. Hue: colour attribute that describes pure colour whereas saturation is the measure of the degree to which a pure colour is diluted by white light. hsv. ntsc.3 [min(R. Step 3 Observe the output images. Step 3 Observe the output image . cmunique and rgbplot commands. and Lab forms. G. Step 2 Perform the colour map manipulation using brighten. lab plane. Colour image manipulation: Step 1 Read the input image. yCbCr. b-‐plane. Randomly reorders the colors in map to produce a new colormap S = 1− Imapprox: Approximate indexed image by reducing number of colors ALGORITHM: To display colour images and individual colour elements: Step 1 Read the input RGB image Step 2 Display the image in rgb. cmpermute. g-‐plane. Separate the individual colour elements like r-‐plane. yq plane. B )] (R + G + B ) I = 13 (R + G + B ) Cmunique: Eliminate duplicate colors in colormap and convert grayscale or truecolor image to indexed image Cmpermute: Rearrange colors in colormap. hsv plane. title('YCBCR'). 2).10). img6=img1(: . img9=img2(: . imshow(img2). img5=img1(: . Red=img1.Green=img1. imshow(img7). :. subplot(554). img3=rgb2ycbcr(img1). title('SATURATION'). subplot(556).1). imshow(img8).5.COLOR IMAGE PROCESSING img1=imread('peppers. title('HSV'). title('VALUE'). subplot(558). : . imshow(img6). title('HUE'). : . . imshow(img10).Blue=img1. subplot(555). : . img2=rgb2hsv(img1). subplot(5. imshow(img1). imshow(img9). 2). : . : . subplot(5. title('Original image').png'). Red(:. imshow(img4). img8=img2(: . subplot(551). imshow(img3). img10=img2(: . 3).5.2:3)=0. img7=img1(: . imshow(img5).11). subplot(557). 1). title('NTSC'). img4=rgb2ntsc(img1).:. subplot(552). subplot(559). subplot(553). 3). : . j=img3(: . . Green(:. title('CR COMPONENT').13). title('GREEN COMPONENT').12).14).:.5. imshow(l). subplot(5. Blue(:.5.16). title('RED COMPONENT'). imshow(j).15). k=img3(: .5.2).5. title('CB COMPONENT').1:2)=0. subplot(5.5.: .: .3).imshow(Red). subplot(5.1)=0. subplot(5. imshow(Blue). l=img3(: . subplot(5. title('Y COMPONENT'). title('BLUE COMPONENT').1). imshow(k).:. imshow(Green). OUTPUT CONVERSION BETWEEN COLOR SPACE . COLOUR IMAGE PROCESSING-‐ II DATE: AIM: To write a MATLAB program to perform colour conversion of colour images into various formats. Step 5 Observe the output image . makecform also supports conversions to and from the sRGB and CMYK color spaces Applycform: Apply device-‐independent color space transformationB = applycform(A. xyz2xyl. (International Commission on Illumination). Step 2 Perform image conversions using functions makecform andapplycform. Makecform supports conversions between members of the family of device-‐ independent color spaces defined by the CIE. SOFTWARES USED MATLAB Version 2013a THEORY: Makecform: Create color transformation structure C = makecform (type)creates the color transformation structure C that defines the color space conversion specified by type. xyz2lab. Step 4 Perform conversions like srgb2lab. To perform the transformation. The type argument specifies one of the conversions listed in the following table. lab2srgb. In addition.EX NO. Step 3 Take the inverse Fourier transform to get the filtered image. pass the color transformation structure as an argument to the applycformfunction. The color transformation structure specifies various parameters of the transformation. ALGORITHM: Step 1 Read the input image.C) converts the color values in A to the color space specified in the color transformation structureC. xyz2uvl. img8temp). img11=applycform(img2. img3=makecform('srgb2lab'). title('UVL2XYZ'). subplot(337). img10temp=makecform('xyz2uvl'). img5temp=makecform('lab2srgb'). img10=applycform(img2.img11temp). subplot(331). img5=applycform(img2. title('LAB2LCH').IMAGE TYPE CONVERSION img1=imread('onion. img11temp=makecform('xyl2xyz').png'). img9temp=makecform('lab2lch').img7temp). img8temp=makecform('lch2lab'). subplot(336).img5temp). img6=applycform(img2. subplot(335). title('LAB2SRGB'). imshow(img5). img2=double(img1). imshow(img8). imshow(img7). img7temp=makecform('uvl2xyz').img9temp). subplot(333). imshow(img4). img7=applycform(img2. . imshow(img10). title('SRGB2XYZ'). title('SRGB2LAB'). img4=applycform(img2. title('LCH2LAB'). subplot(338). title('XYZ2UVL'). img9=applycform(img2. imshow(img9). img6temp=makecform('srgb2xyz').img10temp). subplot(334).img6temp).img3). imshow(img6). img8=applycform(img2. subplot(332). title('Original image'). image(X). title('XYZ2LAB'). subplot(339). title('RGB plot of image after cmpermute'). CMUNIQUE load trees subplot(121). image(Y).index]=sort(hsvmap(:. imshow(img12). rgbplot(map). [dum. title('Image after cmpermute'). subplot(221). rgbplot(newmap).newmap]=cmpermute(X. colormap(map). CMPERMUTE load trees hsvmap=rgb2hsv(map). rgbplot(newmap). title('XYL2XYZ'). . subplot(224). img12=applycform(img2. subplot(222).newmap]=cmunique(X. subplot(224).map. subplot(223).imshow(img11). title('Original image'). colormap(map).img12temp). title('RGB plot of map'). [Y. [Y. image(X). img12temp=makecform('xyz2lab'). figure.map).index). title('Image after cmpermute'). axis image.3)). axis off. colormap(newmap). title('Image after cmapprox'). image(Y). axis image. image(X). axis off.newmap]=imapprox(X. [Y.0. title('Image after cmunique'). axis off. . colormap(newmap).map.subplot(122). colormap(newmap). CMAPPROX load trees subplot(121). image(Y). axis image.5) subplot(122). axis off. title('Original image'). colormap(map). axis image. IMAGE TYPE CONVERSION CMPERMUTE . CMUNIQUE CMAPPROX . φ(x) ΨD(x. and Translatability. φ(y) ΨV(x.EX NO: WAVELET BASED IMAGE COMPRESSION DATE: AIM: To write a MATLAB program to perform second level decomposition on image using a) Haar wavelets. The kernels can be represented as three separable 2-‐D wavelets and one separable 2-‐D scaling function. The various transforms are related by the fact that their expansion functions are “small waves” of varying frequency and limited duration Each wavelet possesses the following general properties: Separability.y) = Ψ(x). b) Daubechies wavelet and c) Bi-‐orthogonal wavelets SOFTWARES USED: MATLAB Version 2013a THEORY: The term DWT refers to a class of transformations that differ not only in the transformation kernels employed. Ψ (y) . ΨH(x.y) = Ψ(x).y) = Ψ(y). Scalability. but also in the fundamental nature of those functions and in the way in which they are applied. square-‐ integrable functions. The set of functions that can be represented as a series expansion of Φj. vertical and diagonal wavelets respectively and one separable 2-‐D scaling function.ΨV(x. d. gs ˃ = δrs = 1 r=s 0 otherwise And g is called the dual of h. The only function that can be represented at every scale is f(x)=0.v… for real. That is. extracting every other point from a sequence of points.y)= φ(x).y) . φ(y) Each of these 2-‐D functions is the product of two 1-‐D real.k is orthogonal to its integer translates. The expansion functions form an orthonormal or biorthogonal basis for the set of 1-‐D measurable. gu.k(x)=2j/2 Ψ(2j x-‐k) Multiresolution Compatibility. respectively. ˂hr. orthonormal kernels. The 1-‐D scaling function just introduced satisfies the following requirements of multiresolution analysis: a.k(x) and Φ"j. Φj. can represent the difference between any two sets of Φj.k(x) and Φj.k. .k representable functions at adjacent scales. foe biorthogonal wavelet transform with scaling and wavelet functions Ψ l. hφ(-‐n) Lowpass decomposition filters hΨ(-‐m) Highpass decomposition filters Block containing a 2 & 2 a down arrow represent downsampling.k at low scales or resolutions is contained within those that can be represented at higher scales. Orthogonality. Φj. The fourier kernels. φ(x. via the series expansions.ΨH(x. Fast wavelet transform: An important consequence of the above properties is that both Ψ(x) and φ(x) can be expressed as linear combinations of double-‐ resolution copies of themselves.v…=hu.y) . b. square-‐integrable scaling and wavelet functions. Any function can be represented with arbitrary precision as j→∞ Wavelet Ψj.ΨD(x.k(x) =2j/2 Φ(2j x-‐k) Ψ l.√2 φ(2x-‐n) Ψ(x) = ΣhΨ(n). c. together with its integer translates and binary scalings.To be called a basis there must be a unique set of expansion coefficients for every representable function.√2 Ψ(2x-‐n) Where hφ and hΨ are called scaling and wavelet vectors.k(x) respectively.y) are called horizontal. φ(x) = Σhφ(n). For the biorthogonal case.k(x) the duals are denoted Ψ" l. 𝑦)𝛹!.!.m.m.!. Salient features of wavelets: Time and frequency resolution using wavelets .! (𝑥. We can apply wavelet domain filtering methods after taking the wavelet transform of an image. Compute the inverse.n)|n=2k. WΨH(j.m.n) = 1/√MN[ !!! !!! !!! 𝜑!. 𝑦)𝛹!. 𝑦)] !!! !!! The 2-‐D forward wavelet transform can be computed in a fast way using an analysis filter bank.!.m.n) = 1/√MN[ WΨH(j.! (𝑥.! (𝑥.V. 𝑦)𝛹!. 𝑦)] ! !!! !!! !!! !!! 𝑓(𝑥.m.D } are horizontal.m.n) = 1/√MN[ WΨD(j.! (𝑥. 𝑦)] WΨi(j.n) = hΨ(-‐m)*[ hφ(-‐n)*Wφ(j+1. for example. 𝑦)𝛹!.n) = 1/√MN[ ! !!! !!! 𝑓(𝑥. Compute the 2-‐D wavelet transform of an image.m. The coefficients are created via two lowpass filters are thus called approximation coefficients { WΨi for i=H.!.n) in the above figure.! (𝑥.!. 𝑦)] ! !!! !!! !!! !!! 𝑓(𝑥. Make modifications to the transform coefficients. Mathematically. 𝑦)] ! !!! !!! !!! !!! 𝑓(𝑥.n) = 1/√MN[ WΨV(j.k≥0] |m=2k.m. the series of filtering and downsampling operations used to compute WΨH(j. DWT scaling vectors behave as lowpass filters and DWT wavelet vectors behave as highpass filters. vertical and diagonal detail coefficients respectively !!! Wφ(j. k≥0 The input to the filter bank is decomposed into four lower resolution components. A wavelet basis function can be translated anywhere in the spatial domain. Step 11 Find out the approximate coefficients using appcoef. The translated and scaled versions of these basis functions are used to detect and localise different frequency components in an image. perform wavedec2 command and obtain the coefficients. Step 2 Generate the wavelet transform coefficient using dct2 command. A basis function at a higher scale can detect a high frequency in the image content. Step 8 For HPF reconstruct the last few values from the coefficients and display the reconstructed output. Step 5 Display the transformed image and input image. The wavelet’s ability to capture multiple levels of details makes it possible to have multiresolution decomposition of the image. Localization of this high frequency is made possible by noting the translation of the basis function. Step 9 For wavelet based denoising and Gaussian noise to the input. It can also have multiple scaled versions with the adjacent scales related by a factor of 2. Step 3 Generate a matrix from the obtained coefficient. Step 4 Perform the operation consecutively for progressive levels of compression. Basis functions at higher scales can take note of rapid variations in the signal and thus can capture high level of detail. Step 7 Separate out the first few coefficients and reconstruct the image using waverec2 command. Step 10 Set a threshold and filter the noise and reconstruct the image. ALGORITHM Step 1 Read the input image from the MATLAB directory. . Step 6 For LPF operation. Basis function at lower level scale can capture a lower level of detail. Multiresolution property of wavelet transform The concept of scale is close to concept of frequency interpretation in terms of capturing the level of detail. []).imshow(wav1.q1.'bior3.r1.tif').s1]. subplot(222).title('Daubechies DWT Decimation').r1.[]).imshow(wav3.s1].q1.'bior3.[]).[]).'db3').s]. img1=imread('pout.q.title('Original').r1. clear. clear.r1. [p1.r. subplot(221).q.imshow(wav1.imshow(img1). wav3=idwt2(p1.r1.r. subplot(221).'db3'). [p.'haar').title('Reconstructed').'db3'). [p1. wav1=[p.r1.5'). wav2=[p1.'haar').imshow(wav3.title('Biorthogonal DWT Decimation').s1]=dwt2(p.[]).r1.q1. img1=imread('pout. subplot(224).q.q1.q1.s].s]=dwt2(img1.s]=dwt2(img1.r. subplot(223).title('DWT Decimation').[]). USING BIORTHOGONAL clc.r.imshow(wav2.s].q1. subplot(223).r1.imshow(img1).r1.title('Original').title('Daubechies Reconstructed'). wav3=idwt2(p1.[]). subplot(224).title('Biorthogonal DWT Decimation').tif').q.s1]=dwt2(p. wav2=[p1. USING DOUBECHIES clc.[]). img1=imread('pout. wav1=[p. subplot(223).s1.5'). wav2=[p1.'haar').s]=dwt2(img1.q1.tif').r. [p1.'bior3.title('Daubechies DWT Decimation').s1].imshow(wav2. subplot(224).s1.imshow(img1).s1. .s1]=dwt2(p.q1. subplot(221). [p.q1.imshow(wav2.r.imshow(wav1. wav1=[p. [p.q. clear.title('Original').title('Biorthogonal Reconstructed').imshow(wav3.5').[]). subplot(222). subplot(222).DISCRETE WAVELET TRANSFORM USING HAAR clc. wav3=idwt2(p1.q.title('DWT Decimation'). OUTPUT USING HAAR USING DOUBECHIES . USING BIORTHOGONAL . Similarity . The image segmentation algorithm is based on two basic properties of intensity values i. DisContinuity ii.EX NO IMAGE SEGMENTATION USING WATERSHED TRANSFORMATION DATE AIM To write a MATLAB code to perform a) Detection of lines and points b) Thresholding operations on image using watershed transformation SOFTWARE USED MATLAB Version 2013a THEORY Image segmentation is the process of subdividing an image into its constituents parts or region. Step 2 Convolve the required mask with the input image for detecting horizontal. a) Step edge b)Ramp edge c) Roof edge a) STEP EDGE: Digital step edges are used frequently as edge as edge models in algorithm development. The three methods based on whether they gather their evidence at local level. set a threshold of your choice depending on the pixel values and perform thresholding . A step edge is considered as ideal b) RAMP EDGE Used when the edges are blurred due to defocussing and noisy due to electronic components. 1. regional level or global level. vertical. lines and points using the imfiller command Step 3 To perform optimal thresholding. The edge pixels by themselves cannot segment an image. find out the gray level thresholding value using graythresh command Step 4 Perform thresholding of the input image using im2low command and display the output Step 5 To perform local thresholding. divide the image into blocks using blkproc command Step 6 Find the localized threshold and perform threshold of individual blocks. diagonal. Ramp is practical edge model c) ROOF EDGE Digitization of line drawings in thin features results in roof edges Edge Linking ( Region Boundary decision ) An edge detection procedure identifies the set of edge points. Global processing 3. Local processing 2. ALGORITHM Step 1 Read the input from Matlab directory. Step 7 To find the global threshold. Regional processing using the hough transform. subplot(224).imshow(img1).'salt & pepper'.WATERSHED TRANSFORM clc. subplot(221).title('Image 1'). OUTPUT . wa2=watershed_old(img2. img2=imnoise(img1. img1=checkerboard(40). clear.6).imshow(wa2).title('Image 2').6).title('Watershed of Image 1'). wa1=watershed_old(img1.0. subplot(223).imshow(img2).1).imshow(wa1). subplot(222).title('Watershed of Image 2').
Report "BM2406 Digital Image Processing Lab Manual"