ll = dir('lab3pic/*.jpg'); addpath ./lab3pic/ I = imread(ll(1).name); figure, imshow(I); type ColorGradients.m % Compute color gradients, use p order binomial filter, and threshold t function [Gx,Gy,m] = ColorGradients(I,p,t); Ir = BiSmooth(I(:,:,1),p); Ig = BiSmooth(I(:,:,2),p); Ib = BiSmooth(I(:,:,3),p); [rx,ry] = Gradient(Ir, p); [gx,gy] = Gradient(Ig, p); [bx,by] = Gradient(Ib, p); cx = rx+gx+bx; cy = ry+gy+by; aa = rx.^2 + gx.^2 + bx.^2; cc = ry.^2 + gy.^2 + by.^2; tr = aa + cc; % eigenvalues cannot be bigger than a+c (trace) ind = find(tr >= t); Gx = zeros(size(rx)); Gy = zeros(size(rx)); m = zeros(size(rx)); % NEW Vectorized implementation: 2x2 eigenvalues and eigenvectors computed % directly %eigenvalues a = aa(ind); c = cc(ind); b = rx(ind).*ry(ind) + gx(ind).*gy(ind) + bx(ind).*by(ind); D = sqrt((a+c).^2 - 4*(a.*c-b.^2)); lmax = 0.5*((a+c) + D); % lmin = 0.5*((a(ind)+c(ind)) - D); % eigenvectors ex = zeros(length(ind),1); ey = zeros(length(ind),1); % zero out low threshold edges % ind1 = find(lmax0); ex(ind1) = 1; xx = a - lmax; ind1 = find((lmax>0) & (abs(xx)>=0.00001)); % compute normalized eigenvectors x = -b(ind1)./xx(ind1); xd = 1./sqrt(x.^2+1); ex(ind1) = x.*xd; ey(ind1) = xd; ind1 = find((ex.*cx(ind)+ey.*cy(ind))<0); ex(ind1) = -ex(ind1); ey(ind1) = -ey(ind1); m(ind) = sqrt(lmax); Gx(ind) = ex.*m(ind); Gy(ind) = ey.*m(ind); % % OLD NON-VECTORIZED VERSION: eigenvalues and eigenvectors computed using % eig; may be a bit slow due to the sequential nature of the implementation % % Gx1 = zeros(size(rx)); % Gy1 = zeros(size(rx)); % m1 = zeros(size(rx)); % a = rx.^2 + gx.^2 + bx.^2; % c = ry.^2 + gy.^2 + by.^2; % b = rx.*ry + gx.*gy + bx.*by; % length(ind) % % for i=1:length(ind), % S = [a(ind(i)) b(ind(i)); b(ind(i)) c(ind(i))]; % [V,D] = eig(S); % if (D(2,2) > D(1,1)) % m11 = D(1,1); % D(1,1) = D(2,2); % D(2,2) = m11; % e = V(:,1); % V(:,1) = V(:,2); % V(:,2) = e; % end; % m1(ind(i)) = sqrt(D(1,1)); % e = V(:,1)*m1(ind(i)); % Gx1(ind(i)) = e(1); % Gy1(ind(i)) = e(2); % if (cx(ind(i))*Gx1(ind(i))+cy(ind(i))*Gy1(ind(i))<0) % Gx1(ind(i)) = -Gx1(ind(i)); % Gy1(ind(i)) = -Gy1(ind(i)); % end; % end; % % Gx = Gx1; % Gy = Gy1; % m = m1; [Gx,Gy,m] = ColorGradients(I,2,2); X = 1 2 1 c = 4 X = 1 2 1 c = 4 X = 1 2 1 c = 4 figure, imagesc(m); colorbar figure, imhist(uint8(m)) max(max(m)) ans = 138.8986 help imthresh imthresh not found. Use the Help browser Search tab to search the documentation, or type "help help" for help command options, such as help for methods. help imahes imahes not found. Use the Help browser Search tab to search the documentation, or type "help help" for help command options, such as help for methods. help images Image Processing Toolbox Version 6.1 (R2008a) 23-Jan-2008 Image display and exploration. colorbar - Display colorbar (MATLAB Toolbox). image - Create and display image object (MATLAB Toolbox). imagesc - Scale data and display as image (MATLAB Toolbox). immovie - Make movie from multiframe image. implay - Play movies, videos, or image sequences. imshow - Display image in Handle Graphics figure. imtool - Display image in the Image Tool. montage - Display multiple image frames as rectangular montage. movie - Play recorded movie frames (MATLAB Toolbox). subimage - Display multiple images in single figure. warp - Display image as texture-mapped surface. Image file I/O. analyze75info - Read metadata from header file of Mayo Analyze 7.5 data set. analyze75read - Read image file of Mayo Analyze 7.5 data set. dicomanon - Anonymize DICOM file. dicomdict - Get or set active DICOM data dictionary. dicominfo - Read metadata from DICOM message. dicomlookup - Find attribute in DICOM data dictionary. dicomread - Read DICOM image. dicomuid - Generate DICOM Unique Identifier. dicomwrite - Write images as DICOM files. dicom-dict.txt - Text file containing DICOM data dictionary (2007). dicom-dict-2005.txt - Text file containing DICOM data dictionary (2005). hdrread - Read Radiance HDR image. imfinfo - Information about image file (MATLAB Toolbox). imread - Read image file (MATLAB Toolbox). imwrite - Write image file (MATLAB Toolbox). interfileinfo - Read metadata from Interfile files. interfileread - Read images from Interfile files. isnitf - Check if file is NITF. nitfinfo - Read metadata from NITF file. nitfread - Read NITF image. Image arithmetic. imabsdiff - Absolute difference of two images. imadd - Add two images or add constant to image. imcomplement - Complement image. imdivide - Divide two images or divide image by constant. imlincomb - Linear combination of images. immultiply - Multiply two images or multiply image by constant. imsubtract - Subtract two images or subtract constant from image. ippl - Check for presence of Intel Performance Primitives Library (IPPL). Spatial transformations. checkerboard - Create checkerboard image. findbounds - Find output bounds for spatial transformation. fliptform - Flip input and output roles of TFORM structure. imcrop - Crop image. impyramid - Image pyramid reduction and expansion. imresize - Resize image. imrotate - Rotate image. imtransform - Apply 2-D spatial transformation to image. makeresampler - Create resampling structure. maketform - Create spatial transformation structure (TFORM). tformarray - Apply spatial transformation to N-D array. tformfwd - Apply forward spatial transformation. tforminv - Apply inverse spatial transformation. Image registration. cpstruct2pairs - Convert CPSTRUCT to control point pairs. cp2tform - Infer spatial transformation from control point pairs. cpcorr - Tune control point locations using cross-correlation. cpselect - Control Point Selection Tool. normxcorr2 - Normalized two-dimensional cross-correlation. Pixel values and statistics. corr2 - 2-D correlation coefficient. imcontour - Create contour plot of image data. imhist - Display histogram of image data. impixel - Pixel color values. improfile - Pixel-value cross-sections along line segments. mean2 - Average or mean of matrix elements. regionprops - Measure properties of image regions (blob analysis). std2 - Standard deviation of matrix elements. Image analysis. bwboundaries - Trace region boundaries in binary image. bwtraceboundary - Trace object in binary image. edge - Find edges in intensity image. hough - Hough transform. houghlines - Extract line segments based on Hough transform. houghpeaks - Identify peaks in Hough transform. qtdecomp - Quadtree decomposition. qtgetblk - Get block values in quadtree decomposition. qtsetblk - Set block values in quadtree decomposition. Image enhancement. adapthisteq - Contrast-limited Adaptive Histogram Equalization (CLAHE). decorrstretch - Apply decorrelation stretch to multichannel image. histeq - Enhance contrast using histogram equalization. imadjust - Adjust image intensity values or colormap. imnoise - Add noise to image. medfilt2 - 2-D median filtering. ordfilt2 - 2-D order-statistic filtering. stretchlim - Find limits to contrast stretch an image. intlut - Convert integer values using lookup table. wiener2 - 2-D adaptive noise-removal filtering. Linear filtering. convmtx2 - 2-D convolution matrix. fspecial - Create predefined 2-D filters. imfilter - N-D filtering of multidimensional images. Linear 2-D filter design. freqspace - Determine 2-D frequency response spacing (MATLAB Toolbox). freqz2 - 2-D frequency response. fsamp2 - 2-D FIR filter using frequency sampling. ftrans2 - 2-D FIR filter using frequency transformation. fwind1 - 2-D FIR filter using 1-D window method. fwind2 - 2-D FIR filter using 2-D window method. Image deblurring. deconvblind - Deblur image using blind deconvolution. deconvlucy - Deblur image using Lucy-Richardson method. deconvreg - Deblur image using regularized filter. deconvwnr - Deblur image using Wiener filter. edgetaper - Taper edges using point-spread function. otf2psf - Convert optical transfer function to point-spread function. psf2otf - Convert point-spread function to optical transfer function. Image transforms. dct2 - 2-D discrete cosine transform. dctmtx - Discrete cosine transform matrix. fan2para - Convert fan-beam projections to parallel-beam. fanbeam - Fan-beam transform. fft2 - 2-D fast Fourier transform (MATLAB Toolbox). fftn - N-D fast Fourier transform (MATLAB Toolbox). fftshift - Reverse quadrants of output of FFT (MATLAB Toolbox). idct2 - 2-D inverse discrete cosine transform. ifft2 - 2-D inverse fast Fourier transform (MATLAB Toolbox). ifftn - N-D inverse fast Fourier transform (MATLAB Toolbox). ifanbeam - Inverse fan-beam transform. iradon - Inverse Radon transform. para2fan - Convert parallel-beam projections to fan-beam. phantom - Create head phantom image. radon - Radon transform. Neighborhood and block processing. bestblk - Optimal block size for block processing. blkproc - Distinct block processing for image. col2im - Rearrange matrix columns into blocks. colfilt - Columnwise neighborhood operations. im2col - Rearrange image blocks into columns. nlfilter - General sliding-neighborhood operations. Morphological operations (intensity and binary images). conndef - Default connectivity array. imbothat - Bottom-hat filtering. imclearborder - Suppress light structures connected to image border. imclose - Morphologically close image. imdilate - Dilate image. imerode - Erode image. imextendedmax - Extended-maxima transform. imextendedmin - Extended-minima transform. imfill - Fill image regions and holes. imhmax - H-maxima transform. imhmin - H-minima transform. imimposemin - Impose minima. imopen - Morphologically open image. imreconstruct - Morphological reconstruction. imregionalmax - Regional maxima. imregionalmin - Regional minima. imtophat - Top-hat filtering. watershed - Watershed transform. Morphological operations (binary images). applylut - Neighborhood operations using lookup tables. bwarea - Area of objects in binary image. bwareaopen - Morphologically open binary image (remove small objects). bwdist - Distance transform of binary image. bweuler - Euler number of binary image. bwhitmiss - Binary hit-miss operation. bwlabel - Label connected components in 2-D binary image. bwlabeln - Label connected components in N-D binary image. bwmorph - Morphological operations on binary image. bwpack - Pack binary image. bwperim - Find perimeter of objects in binary image. bwselect - Select objects in binary image. bwulterode - Ultimate erosion. bwunpack - Unpack binary image. makelut - Create lookup table for use with APPLYLUT. Structuring element (STREL) creation and manipulation. getheight - Get STREL height. getneighbors - Get offset location and height of STREL neighbors getnhood - Get STREL neighborhood. getsequence - Get sequence of decomposed STRELs. isflat - True for flat STRELs. reflect - Reflect STREL about its center. strel - Create morphological structuring element (STREL). translate - Translate STREL. Texture analysis. entropy - Entropy of intensity image. entropyfilt - Local entropy of intensity image. graycomatrix - Create gray-level co-occurrence matrix. graycoprops - Properties of gray-level co-occurrence matrix. rangefilt - Local range of image. stdfilt - Local standard deviation of image. Region-based processing. poly2mask - Convert region-of-interest polygon to mask. roicolor - Select region of interest based on color. roifill - Fill in specified polygon in grayscale image. roifilt2 - Filter region of interest. roipoly - Select polygonal region of interest. Colormap manipulation. brighten - Brighten or darken colormap (MATLAB Toolbox). cmpermute - Rearrange colors in colormap. cmunique - Eliminate unneeded colors in colormap of indexed image. colormap - Set or get color lookup table (MATLAB Toolbox). imapprox - Approximate indexed image by one with fewer colors. rgbplot - Plot RGB colormap components (MATLAB Toolbox). Color space conversions. applycform - Apply device-independent color space transformation. hsv2rgb - Convert HSV color values to RGB color space (MATLAB Toolbox). iccfind - Search for ICC profiles by description. iccread - Read ICC color profile. iccroot - Find system ICC profile repository. iccwrite - Write ICC color profile. isicc - True for complete profile structure lab2double - Convert L*a*b* color values to double. lab2uint16 - Convert L*a*b* color values to uint16. lab2uint8 - Convert L*a*b* color values to uint8. makecform - Create device-independent color space transformation structure (CFORM). ntsc2rgb - Convert NTSC color values to RGB color space. rgb2hsv - Convert RGB color values to HSV color space (MATLAB Toolbox). rgb2ntsc - Convert RGB color values to NTSC color space. rgb2ycbcr - Convert RGB color values to YCbCr color space. whitepoint - XYZ color values of standard illuminants. xyz2double - Convert XYZ color values to double. xyz2uint16 - Convert XYZ color values to uint16. ycbcr2rgb - Convert YCbCr color values to RGB color space. Interactive mouse utility functions. getline - Select polyline with mouse. getpts - Select points with mouse. getrect - Select rectangle with mouse. ICC color profiles. lab8.icm - 8-bit Lab profile. monitor.icm - Typical monitor profile. Sequel Imaging, Inc., used with permission. sRGB.icm - sRGB profile. Hewlett-Packard, used with permission. swopcmyk.icm - CMYK input profile. Eastman Kodak, used with permission. Array operations. circshift - Shift array circularly (MATLAB Toolbox). padarray - Pad array. Image types and type conversions. demosaic - Convert Bayer pattern encoded image to a truecolor image. dither - Convert image using dithering. gray2ind - Convert intensity image to indexed image. grayslice - Create indexed image from intensity image by thresholding. graythresh - Global image threshold using Otsu's method. im2bw - Convert image to binary image by thresholding. im2double - Convert image to double precision. im2int16 - Convert image to 16-bit signed integers. im2java - Convert image to Java image (MATLAB Toolbox). im2java2d - Convert image to Java BufferedImage. im2single - Convert image to single precision. im2uint8 - Convert image to 8-bit unsigned integers. im2uint16 - Convert image to 16-bit unsigned integers. ind2gray - Convert indexed image to intensity image. ind2rgb - Convert indexed image to RGB image (MATLAB Toolbox). label2rgb - Convert label matrix to RGB image. mat2gray - Convert matrix to intensity image. rgb2gray - Convert RGB image or colormap to grayscale. rgb2ind - Convert RGB image to indexed image. tonemap - Render high dyanmic range image for viewing. Toolbox preferences. iptgetpref - Get value of Image Processing Toolbox preference. iptsetpref - Set value of Image Processing Toolbox preference. Toolbox utility functions. getrangefromclass - Get dynamic range of image based on its class. iptcheckconn - Check validity of connectivity argument. iptcheckinput - Check validity of array. iptcheckmap - Check validity of colormap. iptchecknargin - Check number of input arguments. iptcheckstrs - Check validity of text string. iptnum2ordinal - Convert positive integer to ordinal string. Modular interactive tools. imageinfo - Image Information tool. imcontrast - Adjust Contrast tool. imdisplayrange - Display Range tool. imdistline - Draggable Distance tool. imgetfile - Open Image dialog box. impixelinfo - Pixel Information tool. impixelinfoval - Pixel Information tool without text label. impixelregion - Pixel Region tool. impixelregionpanel - Pixel Region tool panel. imputfile - Save Image dialog box. imsave - Save Image tool. Navigational tools for image scroll panel. imscrollpanel - Scroll panel for interactive image navigation. immagbox - Magnification box for scroll panel. imoverview - Overview tool for image displayed in scroll panel. imoverviewpanel - Overview tool panel for image displayed in scroll panel. Utility functions for interactive tools. axes2pix - Convert axes coordinate to pixel coordinate. getimage - Get image data from axes. getimagemodel - Get image model object from image object. imagemodel - Image model object. imattributes - Information about image attributes. imhandles - Get all image handles. imgca - Get handle to most recent current axis containing an image. imgcf - Get handle to most recent current figure containing an image. imellipse - Create draggable, resizable ellipse. imfreehand - Create draggable freehand region. imline - Create draggable, resizable line. impoint - Create draggable point. impoly - Create draggable, resizable polygon. imrect - Create draggable, resizable rectangle. iptaddcallback - Add function handle to callback list. iptcheckhandle - Check validity of handle. iptgetapi - Get Application Programmer Interface (API) for handle. iptGetPointerBehavior - Retrieve pointer behavior from HG object. ipticondir - Directories containing IPT and MATLAB icons. iptPointerManager - Install mouse pointer manager in figure. iptremovecallback - Delete function handle from callback list. iptSetPointerBehavior - Store pointer behavior in HG object. iptwindowalign - Align figure windows. makeConstrainToRectFcn - Create rectangularly bounded position constraint function. truesize - Adjust display size of image. Demos. iptdemos - Index of Image Processing Toolbox demos. See also imdemos, imuitools, iptformats, iptutils, medformats. help graythresh GRAYTHRESH Global image threshold using Otsu's method. 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]. GRAYTHRESH uses Otsu's method, which chooses the threshold to minimize the intraclass variance of the thresholded black and white pixels. [LEVEL EM] = GRAYTHRESH(I) returns effectiveness metric, EM, as the second output argument. It indicates the effectiveness of thresholding of the input image and it is in the range [0, 1]. The lower bound is attainable only by images having a single gray level, and the upper bound is attainable only by two-valued images. Class Support ------------- The input image I can be uint8, uint16, int16, single, or double, and it must be nonsparse. LEVEL and EM are double scalars. Example ------- I = imread('coins.png'); level = graythresh(I); BW = im2bw(I,level); figure, imshow(BW) See also im2bw. Reference page in Help browser doc graythresh g = graythresh(uint8(m)) g = 0.1765 g*255 ans = 45 length(find(m>10)) ans = 8623 length(find(m>5)) ans = 16458 [M,N] = size(m) M = 240 N = 320 M*N ans = 76800 length(find(m>45)) ans = 2162 type NMS2.m % This is vectorized version % Non-maximum suppression for a gradient image; % magnitudes under t are ignored % returns a binary image where maximal gradient values are non-zero function [m1] = NMS2(Gx,Gy,m,t); [M,N] = size(Gx); % m = sqrt(Gx.^2+Gy.^2); % magnitude I1 = find(m0); aGx = abs(Gx); aGy = abs(Gy); Z = zeros([M,N]); % binary image for i=1:size(I), if I(i)>1 & I(i)1 & J(i)0 dx = 1; else dx = -1; end; if Gy(I(i),J(i))>0 dy = 1; else dy = -1; end; if aGx(I(i),J(i))>aGy(I(i),J(i)) % x is dominant direction m01 = m(I(i),J(i)+dx); m11 = m(I(i)-dy,J(i)+dx); m_01 = m(I(i),J(i)-dx); m_11 = m(I(i)+dy,J(i)-dx); m1 = (aGx(I(i),J(i))-aGy(I(i),J(i)))*m01 + aGy(I(i),J(i))*m11; m2 = (aGx(I(i),J(i))-aGy(I(i),J(i)))*m_01 + aGy(I(i),J(i))*m_11; mag = m(I(i),J(i))*aGx(I(i),J(i)); if (mag>m2) & (mag>=m1) Z(I(i),J(i)) = 1; end else % y is dominant direction m01 = m(I(i)-dy,J(i)); m11 = m(I(i)-dy,J(i)+dx); m_01 = m(I(i)+dy,J(i)); m_11 = m(I(i)+dy,J(i)-dx); m1 = (aGy(I(i),J(i))-aGx(I(i),J(i)))*m01 + aGx(I(i),J(i))*m11; m2 = (aGy(I(i),J(i))-aGx(I(i),J(i)))*m_01 + aGx(I(i),J(i))*m_11; mag = m(I(i),J(i))*aGy(I(i),J(i)); if (mag>m2) & (mag>=m1) Z(I(i),J(i)) = 1; end end end % if end % for I1 = find(Z==0); % only keep points where Z=1 m(I1)=0; m1 = uint8(m); m1 = NMS2(Gx,Gy,m,5); lenght(find(m1>0)) ??? Undefined function or method 'lenght' for input arguments of type 'double'. length(find(m1>0)) ans = 4976 type Hysteresis.m % Hysteresis thresholding: keep all points with m>t connected to % points with m>t2 (=2.5t) function [m1] = Hysteresis(m, t) [L, numc] = bwlabel(m); t2 = 2.5*t; [I,J] = find((L>0) & (m>t2)); % find labeled points with mag>t2 comps = zeros(numc,1); % initialize comps for i=1:size(I), % components with at least one point mag.>t2 comps(L(I(i),J(i))) = 1; end [I,J] = find(L>0); % find non-zero points for i=1:size(I), L(I(i),J(i)) = comps(L(I(i),J(i))); %replace connected components labels end; m1 = zeros(size(m)); % initialize m I2 = find(L>0); % L can be treated as a vector m1(I2) = m(I2); % for i=1:numc, % remove connected components that are too small % i, comps(i) % if comps(i)>0 % ind = find(L == i); % i, length(ind) % if (length(ind) < MinEdgeLen) % comps(i) = 0; % end; % end; % end; m2 = Hysteresis(m1,5); length(find(m2>0)) ans = 3724 figure, imagesc(m2); figure, imshow(m2>0); m2 = Hysteresis(m1,3); figure, imshow(m2>0); ind = find(m2>0); alpha = atan2(Gy(ind),Gx(ind)); figure,hist(alpha,36); ind2=find(alpha<0); alpha(ind2) = alpha(ind2)+2*pi; whos alpha Name Size Bytes Class Attributes alpha 4546x1 36368 double ei = rint(alpha/10); ??? Undefined function or method 'rint' for input arguments of type 'double'. ei = round(alpha/10); ei = round(alpha*18/pi); max(ei) ans = 36 min(ei) ans = 0 ind2 = find(ei == 0); ei(ind2) = 36; m3(ind) = m(ind); clear m3 m3 = m(ind); whos m3 ei Name Size Bytes Class Attributes ei 4546x1 36368 double m3 4546x1 36368 double h1 = histc(ei,0:36); sum(h1) ans = 4546 figure, stem(h1); figure, stem(h1);clear h1 max(max(ei)) ans = 36 max(ei) ans = 36 h1(37) ??? Undefined function or method 'h1' for input arguments of type 'double'. h1 ??? Undefined function or variable 'h1'. h1 = histc(ei,1:36); whos h1 Name Size Bytes Class Attributes h1 36x1 288 double h1(1) ans = 81 h1(36) ans = 356 sum(h1) ans = 4546 h2 = zeros(size(h1)) h2 = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 for i=1:36, ind2 = find(ei==i); h2(i) = sum(m3(ind2)); end; figure, stem(h2); figure, stem(h1); help histc HISTC Histogram count. N = HISTC(X,EDGES), for vector X, counts the number of values in X that fall between the elements in the EDGES vector (which must contain monotonically non-decreasing values). N is a LENGTH(EDGES) vector containing these counts. N(k) will count the value X(i) if EDGES(k) <= X(i) < EDGES(k+1). The last bin will count any values of X that match EDGES(end). Values outside the values in EDGES are not counted. Use -inf and inf in EDGES to include all non-NaN values. For matrices, HISTC(X,EDGES) is a matrix of column histogram counts. For N-D arrays, HISTC(X,EDGES) operates along the first non-singleton dimension. HISTC(X,EDGES,DIM) operates along the dimension DIM. [N,BIN] = HISTC(X,EDGES,...) also returns an index matrix BIN. If X is a vector, N(K) = SUM(BIN==K). BIN is zero for out of range values. If X is an m-by-n matrix, then, for j=1:n, N(K,j) = SUM(BIN(:,j)==K); end Use BAR(EDGES,N,'histc') to plot the histogram. Example: histc(pascal(3),1:6) produces the array [3 1 1; 0 1 0; 0 1 1; 0 0 0; 0 0 0; 0 0 1] Class support for inputs X,EDGES: float: double, single See also hist. Reference page in Help browser doc histc diary