Tách Biên Và Phân Vùng Ảnh

download Tách Biên Và Phân Vùng Ảnh

of 103

Transcript of Tách Biên Và Phân Vùng Ảnh

  • TCH BIN V PHN VNG NH*

  • PHN NGNG THRESHOLDINGPhn ngng dng tch mt vt ra khi nh nnXt histogram nh xm bn diTa c th kt lun nh nh phn trng ca vt ng vi f(x,y) >T v nn en ng vi f(x,y)
  • PHN NGNG THRESHOLDINGNgng T chung cho ton b nh gi l ngng ton cc Chn T bng phng php th sai da vo quan st hoc dng phng php lp sau:Chn gi tr ban u cho T , thng l trung bnh cng cc i v cc tiuPhn on nh dng ngng T c hai nhm G1, G2Tnh cng trung bnh cho mi nhmTnh li T l trung bnh ca hai cng nyLp li bc 3*

  • PHN NGNG THRESHOLDING*

  • TCH NGNG DNG PHNG PHP OTSUOtsu neu ra phng phap e anh gia phng sai gia hai lp. Nhng pixel cua anh co gia tr cng o trong day L gia tr mc xam [0,1,2, ,L], so lng pixel mc i la ni va tong so pixel cua anh la

    e n gian van e, bieu o Histogram c bien oi va xem nh la mot phan bo xac xuat:*

  • TCH NGNG DNG PHNG PHP OTSUCc im nh chia lm hai lp C0 v C1 bi gi tr k, C0 ai dien cho nhng pixel co cng o trong khoang [0 ;k-1], va C1 ai dien cho nhng pixel co cng o trong khoang [k ; L-1].K chn cc i phng sai gia lp *

  • TCH NGNG DNG PHNG PHP OTSUMatlab c hm graythres cho gi tr ngng theo pp ny

    Ga tr T ny dng trong hm mbw i nh xm ra nh nh phn*

  • TCH NGNG DNG PHNG PHP OTSUI = imread('coins.png');imshow(I)level = graythresh(I);BW = im2bw(I,level);figure, imshow(BW)*

  • PHN NGNG CC B (PHN NGNG THCH NGHI)Nu chiu sng thay i vic phn ngng c th saiDng ngng thch nghi thay i theo im nh khc phc f0 l opening ca f v T0 l ngng do hm graythresh tc ng ln f0*

  • PHN NGNG DNG OPENCVdouble cvThreshold( CvArr* src, CvArr* dst, double threshold, double max_value, int threshold_type);#include #include #include void sum_rgb( IplImage* src, IplImage* dst ) { // Allocate individual image planes. IplImage* r = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 ); IplImage* g = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 );*

  • PHN NGNG DNG OPENCV IplImage* b = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 ); // Split image onto the color planes. cvSplit( src, r, g, b, NULL ); // Temporary storage. IplImage* s = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 ); // Add equally weighted rgb values. cvAddWeighted( r, 1./3., g, 1./3., 0.0, s ); cvAddWeighted( s, 2./3., b, 1./3., 0.0, s );*

  • PHN NGNG DNG OPENCV// Truncate values above 100. cvThreshold( s, dst, 100, 100, CV_THRESH_TRUNC ); cvReleaseImage( &r ); cvReleaseImage( &g ); cvReleaseImage( &b ); cvReleaseImage( &s );}int main(int argc, char** argv){ // Create a named window with the name of the file. cvNamedWindow( argv[1], 1 ); // Load the image from the given file name. IplImage* src = cvLoadImage( argv[1] ); *

  • PHN NGNG DNG OPENCVIplImage* dst = cvCreateImage( cvGetSize(src), src->depth, 1); sum_rgb( src, dst);// Show the image in the named window cvShowImage( argv[1], dst ); // Idle until the user hits the Esc key. while( 1 ) { if( (cvWaitKey( 10 )&0x7f) == 27 ) break; } // Clean up and dont be piggies cvDestroyWindow( argv[1] );cvReleaseImage( &src ); cvReleaseImage( &dst );}*

  • PHN NGNG THCH NGHI DNG OPENCVvoid cvAdaptiveThreshold( CvArr* src, CvArr* dst, double max_val, int adaptive_method = CV_ADAPTIVE_THRESH_MEAN_C int threshold_type = CV_THRESH_BINARY, int block_size = 3, double param1 = 5);*

  • SO SNH PHN NGNG V PHN NGNG THCH NGHI*

  • TCH iM C LPTch im c lp: mt im c lp c th tch bng cch di chuyn mt n 3x3 trn nh, cng im nh tm mt n l tng cc tch cng im nh bao bi mt n vi cc trng s mt n, nu qu mc ngng no th kt lun l im c lpTrong cng thc di z l cng sng, w l trng s mt n, R l cng sng mi, T l ngng khng m Dng dng tch chp*

  • *

  • TCH NGVi cc ng thng dy mt pixel theo chiu ngang dc hay gc 45o ta c th dng cc mt n sau*

  • TCH CNH EDGEThng tim s thay i t ngt ca sng bng phng php gradient, o hm bc mt v bc hai (Laplacian) ca sng*

  • Tm cnh ch o hm bc nht ln hn gia tr ngng hay o hm bc hai bng khng Matlab c hm edge tm cc im cnh ty theo method v parameters, kt qu l ma trn g c gi tr 1 ch cnh v 0 ngc li, v ngng t tng ng, parameters gm ngng T v hng direction Cc php tnh o hm c thay bng cc tch chp vi cc mt n ph hp*

  • *

  • Tch cnh gm ba giai on: lc, vi phn v so ngngVi phn thng dng lc trung bnh hay lc Gauss

    Lc Gauss c tnh khi cho trc sigma v tnh g theo x,y ri chun ha thnh tr nguyn*

  • *

  • LC SOBEL*

  • LC PREWITTLc Prewitt tnh ton n gin hn lc Sobel nhng kt qu khng trn bng*

  • LC ROBERTS*

  • LC LAPLACEThay ton t o hm bc hai bng mt trong cc mt n*

  • LAPLACIAN OF GAUSSIAN LOGNhn chp nh vi o hm bc hai ca hm Gauss *

  • LC CANNYPhng php lc tt nht, gm cc bc:Lc GaussTnh gradient v hng, im cnh ng vi gradient ti a theo hng gradientSo snh vi hai ngng T1 < T2*

  • *

  • *

  • *

  • BiN I HOUGHSau khi tm cc im cnh ta ni chng li to bin dng bin i HoughCho hai im cnh (xi,yi) v (xj,yj) ta tm phng trnh ng thng ni hai im ny Tm v *

  • *

  • BiN I HOUGHCho v thay i trong phm vi gii hn v c gi tr ri rc, ta to ma trn tch ly A(,) c gi tr ban u 0 Vi mi v im cnh (xi,yi) ta tnh , A(,) tng ng s tng thm 1Tm cp (,) ng vi A cc i, c ngha l c nhiu ng i qua im cnh c cng (,), c ngha l cc ng ny trng nhau, vy ta to c ng thng ni cc im cnh v (,) xc nh mt ng thng duy nht *

  • *

  • *

  • V D MATLAB BiN I HOUGHHm hough to ma trn H(,) dng bin i Hough tiu chun SHT[H, theta, rho] = hough(BW)[H, theta, rho] = hough(BW, ParameterName, ParameterValue)RGB = imread('gantrycrane.png'); % Convert to intensity. I = rgb2gray(RGB); % Extract edges. BW = edge(I,'canny'); [H,T,R] = hough(BW,'RhoResolution',0.5,'Theta',-90:0.5:89.5); % Display the original image. subplot(2,1,1); imshow(RGB); title('Gantrycrane Image');

    *

  • V D MATLAB BiN I HOUGH% Display the Hough matrix. subplot(2,1,2); imshow(imadjust(mat2gray(H)),'XData',T,'YData',R,... 'InitialMagnification','fit'); title('Hough Transform of Gantrycrane Image'); xlabel('\theta'), ylabel('\rho'); axis on, axis normal, hold on; colormap(hot);

    *

  • V D MATLAB BiN I HOUGHHm houghpeaks tm gi tr cc i trong ma trn Hough, tr v ta hng ct ca im cc i, numpeaks l s im cc i mun tm peaks = houghpeaks(H, numpeaks) peaks = houghpeaks(..., param1, val1, param2, val2)%Read an image into the MATLAB workspace.I = imread('circuit.tif');%For this example, rotate and crop the image using the imrotate function.rotI = imrotate(I,33,'crop'); fig1 = imshow(rotI);%Find the edges in the image using the edge function.BW = edge(rotI,'canny'); figure, imshow(BW);%Compute the Hough transform of the image using the hough function.[H,theta,rho] = hough(BW);%Display the transform using the imshow function.*

  • V D MATLAB BiN I HOUGHfigure, imshow(imadjust(mat2gray(H)),[],'XData',theta,'YData',rho,... 'InitialMagnification','fit'); xlabel('\theta (degrees)'), ylabel('\rho'); axis on, axis normal, hold on; colormap(hot)%Find the peaks in the Hough transform matrix, H, using the houghpeaks function.P = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));%Superimpose a plot on the image of the transform that identifies the peaks.x = theta(P(:,2)); y = rho(P(:,1)); plot(x,y,'s','color','black');

    *

  • V D MATLAB BiN I HOUGH*

  • V D MATLAB BiN I HOUGHHm houghlines tch ng thng da trn theta rho do hm hough cung cp v peaks do hm houghpeaksLines cung cp ta im mt ca on thng v gi tr theta rholines = houghlines(BW, theta, rho, peaks)lines = houghlines(..., param1, val1, param2, val2) %Find lines in the image using the houghlines function. lines = houghlines(BW,theta,rho,P,'FillGap',5,'MinLength',7);%Create a plot that superimposes the lines on the original image.figure, imshow(rotI), hold on max_len = 0; for k = 1:length(lines) xy = [lines(k).point1; lines(k).point2]; *

  • V D MATLAB BiN I HOUGHplot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green'); % Plot beginnings and ends of lines plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow'); plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red'); % Determine the endpoints of the longest line segment len = norm(lines(k).point1 - lines(k).point2); if ( len > max_len) max_len = len; xy_long = xy; end end % highlight the longest line segment plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','red');*

  • V D MATLAB BiN I HOUGH*

  • OPEN CV BiN I HOUGHCvSeq* cvHoughLines2( CvArr* image, void* line_storage, int method, double rho, double theta, int threshold, double param1 = 0, double param2 = 0);Image l nh nh phn, method l cc phng php bin i CV_HOUGH_STANDARD, CV_HOUGH_PROBABILISTIC, CV_HOUGH_MULTI_SCALE

    *

  • OPEN CV BiN I HOUGHrho v theta l phn gii theo pixel v radian, threshold l ngng xc nh ngGi tr tr v l rho v theta ca ng hay ta im u v cui ca ng, tham s line_storage tr n a ch ny*

  • THUT TAN HOUGH TM NG TRNVng trn c ba tham s l tm v bn knh, thut ton tm nh sau*

  • THUT TAN HOUGH TM NG TRNPhng trnh ng trn c th vit l

    *

  • THUT TAN HOUGH TM NG TRNCvSeq* cvHoughCircles( CvArr* image,void* circle_storage, int method, double dp, double min_dist, double param1 = 100, double param2 = 300, int min_radius = 0, int max_radius = 0);*

  • THUT TAN HOUGH TM NG TRNUsing cvHoughCircles to return a sequence of circles found in a grayscale image#include #include #include int main(int argc, char** argv) { IplImage* image = cvLoadImage( argv[1], CV_LOAD_IMAGE_GRAYSCALE ); CvMemStorage* storage = cvCreateMemStorage(0); cvSmooth(image, image, CV_GAUSSIAN, 5, 5 ); CvSeq* results = cvHoughCircles( image, storage, CV_HOUGH_GRADIENT, 2, image->width/10 ); *

  • THUT TAN HOUGH TM NG TRNfor( int i = 0; i < results->total; i++ ) { float* p = (float*) cvGetSeqElem( results, i ); CvPoint pt = cvPoint( cvRound( p[0] ), cvRound( p[1] ) ); cvCircle( image, pt, cvRound( p[2] ), CV_RGB(0xff,0xff,0xff) ); } cvNamedWindow( cvHoughCircles, 1 ); cvShowImage( cvHoughCircles, image); cvWaitKey(0);}

    *

  • THUT TAN HOUGH TM NG TRN*

  • THUT TON HOUGH SUY RNGp dng cho mt hnh bt ku tin tm trng tm hnh (centroid)Vi mi im cnh (x,y) tm vect r(x,y)*

  • PHN NH DA THEO VNGPhn nh da theo vng l chia nh thnh nhiu vng khng giao nhau, cc im trong mt vng c tnh cht P chung*

  • PHN NH DA THEO VNG*

  • PHN NH DA VO NG PHN THY (WATERSHED)nh xm c th xem nh mt b mt c ch cao ch thp, ch thp l lu vc (catchment basin) ni cc con sng chy xung, ng phn thy phn chia ranh gii lu vc, cc con sng pht xut t ng phn thy chy ra hai bn. Cc lu vc chnh l cc vng nh v ng phn thy l ranh gii cc vng, tm ng phn thy ta cho nc dng ln cho n khi cc h giao nhau , ng phn thy v ng ranh gii gia cc vng chm nhau biu th cao cc vng trng ta dng bin i khong cch, gi s nn nh en trng l en (0) cc vng c ga tr trng (1), ta ly o nh, sau dng bin i khong cch, cc pixel gi tr 1 c thay bng 0.0, cc pixel gi tr 0 c thay bng khong cch n pixel gi tr 1 gn nht*

  • PHN NH DA VO NG PHN THY (WATERSHED)*

  • *

  • *

  • Cho nh fHm D=bwdist(-f) bin i nh ra nh bin i khong cchHm L=watershed (-D) v ng phn thy, gi tr 0 l ng phn thyw=L==0 c gi tr 1 ng phn thyG=f and (-w) v ng phn thy trn nh gc*

  • *

  • Trc khi dng watershed transform thng bin i nh bng cc b lc nh morphological gradient, closing opening

    *

  • *

  • Bin i Watershed sinh ra nhiu ng bin sai (oversegmentation) *

  • TCH VNG DA THEO MU(V Duy Nht)close all;clear all;Ir = imread ('C:\Exam.jpg');imshow(Ir)title('source image');I = rgb2gray (Ir);figure();imshow(I)title('grey image');level = graythresh(I);BW_UnderRed = im2bw (I, 0.1);figure();imshow(BW_UnderRed)*

  • TCH VNG DA THEO MUtitle(select under red image');BW_OverRed = im2BW (I, 0.4);figure();imshow(BW_OverRed)title(select over red image');BW_Red = BW_UnderRed-BW_OverRed;figure();imshow(BW_Red)title('red image');Edge_Sobel = edge(BW_Red, 'sobel');Edge_Canny = edge(BW_Red, 'canny');figure();imshow(Edge_Sobel)*

  • TCH VNG DA THEO MUtitle('Sobel image');figure;imshow(Edge_Canny)title('Canny image');figure ();subplot(1, 2, 1); imshow(Ir); title('source image');subplot(1, 2, 2); imshow(Edge_Sobel); title('Sobel image');

    *

  • TCH VNG DA THEO MU//Phm Hong Giang#include#include#includeusingnamespace std;unsignedint num_red,i;IplImage *tmp_img;int main(){char name[]="hinhhoc.jpg";//Gan ten file anh vao mang ky tu IplImage* src=cvLoadImage(name,1); // Load anh IplImage* dst=cvCreateImage(cvGetSize(src),8,3); IplImage* copy=cvCreateImage(cvGetSize(src),8,3); //Tao moi 1 anh o dang 8 bit va 3 channel CvScalar s,c; // Tao 2 bien Scalar cout
  • TCH VNG DA THEO MU {for(int j=0;jwidth);j++)//Trong mang 2 chieu cua anh..Chay tu 0 den width cua anh { s=cvGet2D(src,i,j); //Lay gia tri RGB tai diem i,j cua anh nguon gan vao Saclar s//s.val[2]=Kenh R,s.val[1]=Kenh G,s.val[0]=Kenh B if((s.val[2]>210)&&(s.val[1]
  • TCH VNG DA THEO MU {num_red++; c.val[2]=255; // Red c.val[1]=255;// Green c.val[0]=255;// Blue cvSet2D(copy,i,j,c); //Thay doi gia tri cua diem anh va gan cho anh coppy } } }cout
  • TCH VNG DA THEO MU/*------------------------------------------------------------------*/tmp_img=cvCreateImage (cvGetSize (copy), IPL_DEPTH_8U, 1);cvCanny (copy, tmp_img, 50.0, 200.0);cvNamedWindow ("Tach bien", CV_WINDOW_AUTOSIZE);cvShowImage ("Tach bien",tmp_img);/*------------------------------------------------------------------*/cvWaitKey(); //Cho cho den khi nguoi dung nhan 1 phim hoac cvWaitKey(10) se mat sau 10mscvReleaseImage( &src );cvReleaseImage( &copy );cvReleaseImage( &tmp_img );return 0;}

    *

  • TCH VNG DA THEO MU*

  • TCH VNG DA THEO MU*

  • TCH VNG DA THEO MU*

  • MT S HM OPENCVTm trng tm mt vnguse moments to calculate the position of the center of the object. We have to calculate 1st order spacial moments around x-axis and y-axis and the 0th order central moments of the binary image. - 0th order central moments of the binary imageis equal to the white area of the image in pixels. - X coordinate of the position of the center of the object = 1st order spacial moment around x-axis/ 0th order central moment - Y coordinate of the position of the center of the object =1st order spacial moment around y-axis/0th order central momentIf there are 2 or more objects in the image, we cannot use this method. And noise of the binary image is also should be at minimum level to get accurate results.*

  • MT S HM OPENCV-cvMoments(const CvArr* arr, CvMoments* moments, int isBinary=0 )Calculates all of the spacial and central moments up to the third order Arguments -const CvArr* arr - source image which we are going to find the moment CvMoments* moments - Pointer to a memory block to store calculated moments int isBinary - If this argument is equal to non-zero value, all non-zero pixel values are considered as 1 when calculating moments. -cvGetSpatialMoment(CvMoments*ptr, intx_order, inty_order) Retrieve calculated spacial moments from ptr memory blockArguments -CvMoments*ptr - pointer to allocated memory block which store all momentsintx_order - order of x (>=0)inty_order - order of y (>=0)e.g. - cvGetSpatialMoment(moments, 1, 0)retrieves1st order spacial moment around x-axis cvGetSpatialMoment(moments, 0, 1)retrieves1st order spacial moment around y-axis *

  • Tm trng tm mt vng

    -cvGetCentralMoment (CvMoments*ptr, intx_order, inty_order)Retrieve calculated central moments from ptr memory blockArguments -CvMoments*ptr - pointer to allocated memory block which storeall momentsintx_order - order of x (>=0)inty_order - order of y (>=0)e.g. - cvGetCentralMoment(moments, 0, 0)retrieves0th order central moment cvLine (CvArr*img,CvPointpt1,CvPointpt2,CvScalarcolor, intthickness=1)Draw a line between 2 points, pt1 and pt2Arguments -CvArr*img - source imageCvPointpt1 - starting point of the lineCvPointpt2 - ending point of the lineCvScalarcolor - color of the line (in the Blue, Green, Red order)intthickness - thickness of the line in pixels

    *

  • TCH VNG NH GiA HAI MCcvInRangeS Checks that array elements lie between two scalars.void cvInRangeS(const CvArr src, CvScalar lower, CvScalar upper, CvArr dst);src The first source arraylower The inclusive lower boundaryupper The exclusive upper boundarydst The destination array, must have 8u or 8s type, binaryThe function does the range check for every element of the input array:*

  • Object Detection & Tracking using Color

    Simple Example of Detecting Red objectsIn this example, I am going toconvert a video into abinary image based on the red color. (Red color area of the videois assinedto '1' and other area is assigned to '0' in the binary image) #include "stdafx.h #include #include //This function threshold the HSV image and create a binary image IplImage* GetThresholdedImage(IplImage* imgHSV){ IplImage* imgThresh=cvCreateImage(cvGetSize(imgHSV),IPL_DEPTH_8U, 1); cvInRangeS(imgHSV, cvScalar(170,160,60), cvScalar(180,256,256), imgThresh); return imgThresh; } *

  • Object Detection & Tracking using Color int main(){ CvCapture* capture =0; capture = cvCaptureFromCAM(0); if(!capture){ printf("Capture failure\n"); return -1; } IplImage* frame=0; cvNamedWindow("Video"); cvNamedWindow("Ball"); //iterate through each frames of the video while(true){ frame = cvQueryFrame(capture); if(!frame) break; frame=cvCloneImage(frame); cvSmooth(frame, frame, CV_GAUSSIAN,3,3);//smooth the original image usingGaussiankernel

    *

  • Object Detection & Tracking using Color IplImage* imgHSV = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 3); cvCvtColor(frame, imgHSV, CV_BGR2HSV); //Change the color format from BGR to HSV IplImage* imgThresh = GetThresholdedImage(imgHSV); cvSmooth(imgThresh, imgThresh, CV_GAUSSIAN,3,3);//smooth the binary image usingGaussiankernel cvShowImage("Ball", imgThresh); cvShowImage("Video", frame); //Clean up used images cvReleaseImage(&imgHSV); cvReleaseImage(&imgThresh); cvReleaseImage(&frame); //Wait 50mS int c = cvWaitKey(10); //If 'ESC' is pressed, break the loop if((char)c==27 ) break; } *

  • Object Detection & Tracking using ColorcvDestroyAllWindows(); cvReleaseCapture(&capture); return 0; }*

  • PHN BIT HNH DNG DNG CONTOURUsing contours with OpenCV, you can get a sequence of points of vertices of each white patch (White patches are considered as polygons). As example, you will get 3 points (vertices) for a triangle,and 4 points forquadrilaterals. So, you can identify any polygon by the number of vertices of that polygon. You can even identify features of polygons such as convexity, concavity,equilateraland etc by calculating and comparing distances between vertices.*

  • PHN BIT HNH DNG DNG CONTOURWell draw a line along the perimeter of every identified polygon with colors blue for triangle, green forquadrilateralsand red for heptagons.cvFindContours( CvArr*img, CvMemStorage*str, CvSeq**first_contour, intheader_size, intmode, intmethod, CvPointoffset)Find all contours in a binary image Arguments -CvArr*img - Source image (This should be 8 bit single channel). All non-zero pixels are considered as 1 and all zero remain zero.CvMemStorage*str - Memory blocks to store all obtained contoursCvSeq**first_contour - store a pointer to the first contour in the memory block, 'str'intheader_size - size of the sequence headerintmode - mode of retrieval of contours from the image *

  • PHN BIT HNH DNG DNG CONTOUR You have to choose one of the followingCV_RETR_LIST- Retrieves all of the contours and put them in a list CV_RETR_EXTERNAL- Retrieves only the extreme outer contoursCV_RETR_CCOMP- Retrieves all of the contours and organizes them into a two-level hierarchy: on the top level are the external boundaries of the components, on the second level are the boundaries of the holesCV_RETR_TREE- Retrieves all of the contours and reconstructs the full hierarchy of nested contoursintmethod - Approximation method You have to choose one of the followingCV_CHAIN_CODE- Outputs contours in the Freeman chain codeCV_CHAIN_APPROX_NONE- Translates all of the points from the chain code into pointsCV_CHAIN_APPROX_SIMPLE- Compresses horizontal, vertical, and diagonal segments and leaves only their end points

    *

  • PHN BIT HNH DNG DNG CONTOURCV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS- Applies one of the flavors of the Teh-Chin chain approximation algorithm.CV_LINK_RUNS- uses a completely different contour retrieval algorithm by linking horizontal segments of 1s. Only the 'CV_RETR_LIST'retrieval mode can be used with this method.CvPointoffset- Offset by which every contour point should be shifted. This is useful when we have set ROI (Region Of Interest) in the image. Normally we set the offset to 'cvPoint(0,0)'cvApproxPoly( const void*src, intheader_size, CvMemStorage*storage, intmethod, doublepara1, intpara2)Approximate polygonal curves with specified precisionarguments -const void*src - Sequence of pointsintheader_size - size of the sequence headerCvMemStorage*storage - memory block that contains all contours

    *

  • PHN BIT HNH DNG DNG CONTOURintmethod - Approximation method. (The only method, available to use for this argument is 'CV_POLY_APPROX_DP')doublepara1 - approximation accuracyintpara2 - Determineswhether the single sequence should be approximated or all sequences in the same level or belowcvGetSeqElem( const CvSeq*seq, intindex)Returns a pointer to the element of 'seq' at 'indexcvReleaseMemStorage( CvMemStorage**storage)Deallocate memory blocks which have been allocated by 'cvCreateMemStorage()' functioncvCreateMemStorage(int byteSize)Creates memory storage which has the capacity specified by the parameter 'byteSize'. But if byteSize=0, the allocated capacity is the default value(usually 64 Kb) *

  • PHN BIT HNH DNG DNG CONTOURcvContourArea(const CvArr* contour, CvSlice slice)Calculate the area enclosed by sequence of contour points.const CvArr* contour - array of vertices of the contourCvSlice slice - starting and ending point of the contour. 'CV_WHOLE_SEQ' will take the whole contour to calculate the areaThe orientation of contour affects the area sign. So, this function may return a negative value. So, it should be used fabs() function to get the absolute value.fabs(double x)Thisfunctionreturns the absolute value of any floating point number. ( This is a C function, not a OpenCV function)*

  • PHN BIT HNH DNG DNG CONTOURint main() { IplImage* img = cvLoadImage("C:/FindingContours.png"); //show the original image cvNamedWindow("Raw"); cvShowImage("Raw",img); //converting the original image into grayscale IplImage* imgGrayScale = cvCreateImage(cvGetSize(img), 8, 1); cvCvtColor(img,imgGrayScale,CV_BGR2GRAY); //thresholding the grayscale image to get better results cvThreshold(imgGrayScale,imgGrayScale,128,255,CV_THRESH_BINARY); CvSeq* contours; //hold the pointer to a contour in the memory block CvSeq* result; //hold sequence of points of a contour CvMemStorage *storage = cvCreateMemStorage(0); //storage area for all contours //finding all contours in the image cvFindContours(imgGrayScale, storage, &contours, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));*

  • PHN BIT HNH DNG DNG CONTOUR//iterating through each contour while(contours) { //obtain a sequence of points of contour, pointed by the variable 'contour' result = cvApproxPoly(contours, sizeof(CvContour), storage, CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0); //if there are 3 verticesin the contour(It should be a triangle) if(result->total==3 ) { //iterating through each point CvPoint *pt[3]; for(int i=0;i
  • PHN BIT HNH DNG DNG CONTOUR//if there are 4 vertices in the contour(It should be a quadrilateral) else if(result->total==4 ) { //iterating through each point CvPoint *pt[4]; for(int i=0;i
  • PHN BIT HNH DNG DNG CONTOUR//if there are 7 verticesin the contour(It should be a heptagon) else if(result->total ==7 ) { //iterating through each point CvPoint *pt[7]; for(int i=0;i
  • PHN BIT HNH DNG DNG CONTOUR//obtain the next contour contours = contours->h_next; } //show the image in which identified shapes are marked cvNamedWindow("Tracked"); cvShowImage("Tracked",img); cvWaitKey(0); //wait for a key press //cleaning up cvDestroyAllWindows(); cvReleaseMemStorage(&storage); cvReleaseImage(&img); cvReleaseImage(&imgGrayScale); return 0; }*

  • PHN BIT HNH DNG DNG CONTOUR*

  • PHN BIT HNH DNG MU DNG CONTOUR*

  • int main() { IplImage* img = cvLoadImage("C:/DetectingContours.jpg"); //show the original image cvNamedWindow("Original"); cvShowImage("Original",img); //smooth the original image using Gaussian kernel to remove noise cvSmooth(img,img, CV_GAUSSIAN,3,3); //converting the original image into grayscale IplImage* imgGrayScale = cvCreateImage(cvGetSize(img), 8, 1); cvCvtColor(img,imgGrayScale,CV_BGR2GRAY); cvNamedWindow("GrayScale Image"); cvShowImage("GrayScale Image",imgGrayScale);*

  • //smooth the original image using Gaussian kernel to remove noise cvSmooth(img,img, CV_GAUSSIAN,3,3); //converting the original image into grayscale IplImage* imgGrayScale = cvCreateImage(cvGetSize(img), 8, 1); cvCvtColor(img,imgGrayScale,CV_BGR2GRAY); cvNamedWindow("GrayScale Image"); cvShowImage("GrayScale Image",imgGrayScale); //thresholding the grayscale image to get better results cvThreshold(imgGrayScale,imgGrayScale,100,255,CV_THRESH_BINARY_INV); cvNamedWindow("Thresholded Image"); cvShowImage("Thresholded Image",imgGrayScale);*

  • CvSeq* contour; //hold the pointer to a contour CvSeq* result; //hold sequence of points of a contour CvMemStorage *storage = cvCreateMemStorage(0); //storage area for all contours //finding all contours in the image cvFindContours(imgGrayScale, storage, &contour, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0)); //iterating through each contour while(contour) { //obtain a sequence of points of the countour, pointed by the variable 'countour' result = cvApproxPoly(contour, sizeof(CvContour), storage, CV_POLY_APPROX_DP, cvContourPerimeter(contour)*0.02, 0);*

  • //if there are 3 vertices in the contour and the area of the triangle is more than 100 pixels if(result->total==3 && fabs(cvContourArea(result, CV_WHOLE_SEQ))>100 ) { //iterating through each point CvPoint *pt[3]; for(int i=0;ih_next; }*

  • //show the image in which identified shapes are marked cvNamedWindow("Tracked"); cvShowImage("Tracked",img); cvWaitKey(0); //wait for a key press //cleaning up cvDestroyAllWindows(); cvReleaseMemStorage(&storage); cvReleaseImage(&img); cvReleaseImage(&imgGrayScale); return 0; }

    *

  • *

  • Tracking two Triangles in a Video

    *