Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 103

TCH BIN V PHN VNG

NH
1
PHN NGNG THRESHOLDING
Phn ngng dng tch mt vt ra khi nh
nn
Xt histogram nh xm bn di
Ta c th kt lun nh nh phn trng ca vt
ng vi f(x,y) >T v nn en ng vi f(x,y) <T
2
PHN NGNG THRESHOLDING
Ngng T chung cho ton b nh gi l ngng ton
cc
1. Chn T bng phng php th sai da vo quan st hoc
dng phng php lp sau:
2. Chn gi tr ban u cho T , thng l trung bnh cng
cc i v cc tiu
3. Phn on nh dng ngng T c hai nhm G1, G2
4. Tnh cng trung bnh cho mi nhm
5. Tnh li T l trung bnh ca hai cng ny
6. Lp li bc 3
3
PHN NGNG THRESHOLDING
4
TCH NGNG DNG PHNG PHP OTSU
Otsu 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:
5
TCH NGNG DNG PHNG PHP
OTSU
Cc 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
6
TCH NGNG DNG PHNG PHP OTSU
Matlab 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
7
TCH NGNG DNG PHNG PHP OTSU
I = imread('coins.png');
imshow(I)
level = graythresh(I);
BW = im2bw(I,level);
figure, imshow(BW)
8
PHN NGNG CC B (PHN NGNG
THCH NGHI)
Nu chiu sng thay i vic phn ngng
c th sai
Dng 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
9
PHN NGNG DNG OPENCV
double cvThreshold(
CvArr* src,
CvArr* dst,
double threshold,
double max_value,
int threshold_type
);
#include <stdio.h>
#include <cv.h>
#include <highgui.h>
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 );
10
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 );
11
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] );

12
PHN NGNG DNG OPENCV
IplImage* 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 );
}
13
PHN NGNG THCH NGHI DNG
OPENCV
void 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
);
14
SO SNH PHN NGNG V PHN NGNG
THCH NGHI
15
TCH iM C LP
Tch 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 lp
Trong 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
16
17
TCH NG
Vi cc ng thng dy mt pixel theo chiu
ngang dc hay gc 45
o
ta c th dng cc mt
n sau
18
TCH CNH EDGE
Thng tim s thay i t ngt ca sng bng
phng php gradient, o hm bc mt v bc hai
(Laplacian) ca sng
19
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
20
21
Tch cnh gm ba giai on: lc, vi phn v so
ngng
Vi 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
22
23
LC SOBEL
24
LC PREWITT
Lc Prewitt tnh ton n gin hn lc Sobel nhng kt
qu khng trn bng
25
LC ROBERTS
26
LC LAPLACE
Thay ton t o hm bc hai bng mt trong
cc mt n
27
LAPLACIAN OF GAUSSIAN
LOG
Nhn chp nh vi o hm bc hai ca hm
Gauss
28
LC CANNY
Phng php lc tt nht, gm cc bc:
Lc Gauss
Tnh gradient v hng, im cnh ng vi gradient
ti a theo hng gradient
So snh vi hai ngng T1 < T2
29
30
31
32
BiN I HOUGH
Sau khi tm cc im cnh ta ni chng li
to bin dng bin i Hough
Cho hai im cnh (xi,yi) v (xj,yj) ta tm
phng trnh ng thng ni hai im ny
Tm v
33
34
BiN I HOUGH
Cho 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 1
Tm 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

35
36
37
V D MATLAB BiN I HOUGH
Hm 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');

38
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);

39
V D MATLAB BiN I HOUGH
Hm 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.
40
V D MATLAB BiN I HOUGH
figure,
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');

41
V D MATLAB BiN I HOUGH
42
V D MATLAB BiN I HOUGH
Hm houghlines tch ng thng da trn theta rho
do hm hough cung cp v peaks do hm houghpeaks
Lines cung cp ta im mt ca on thng v gi tr
theta rho
lines = 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];
43
V D MATLAB BiN I HOUGH
plot(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');
44
V D MATLAB BiN I HOUGH
45
OPEN CV BiN I HOUGH
CvSeq* 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


46
OPEN CV BiN I HOUGH
rho v theta l phn gii theo pixel v radian, threshold l
ngng xc nh ng
Gi 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
47
THUT TAN HOUGH TM NG TRN
Vng trn c ba tham s l tm v bn knh,
thut ton tm nh sau
48
THUT TAN HOUGH TM NG TRN
Phng trnh ng trn c th vit l

49
THUT TAN HOUGH TM NG TRN
CvSeq* 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
);
50
THUT TAN HOUGH TM NG TRN
Using cvHoughCircles to return a sequence of circles found in a grayscale
image
#include <cv.h>
#include <highgui.h>
#include <math.h>
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
);


51
THUT TAN HOUGH TM NG TRN
for( 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);
}

52
THUT TAN HOUGH TM NG TRN
53
THUT TON HOUGH SUY RNG
p dng cho mt hnh bt k
u tin tm trng tm hnh (centroid)
Vi mi im cnh (x,y) tm vect r(x,y)
54
PHN NH DA THEO VNG
Phn nh da theo vng l chia nh thnh nhiu vng khng
giao nhau, cc im trong mt vng c tnh cht P chung
55
PHN NH DA THEO VNG
56
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
57
PHN NH DA VO NG PHN THY
(WATERSHED)
58
59
60
Cho nh f
Hm D=bwdist(-f) bin i nh ra nh bin i
khong cch
Hm L=watershed (-D) v ng phn thy,
gi tr 0 l ng phn thy
w=L==0 c gi tr 1 ng phn thy
G=f and (-w) v ng phn thy trn nh gc
61
62
Trc khi dng watershed transform thng
bin i nh bng cc b lc nh
morphological gradient, closing opening

63
64
Bin i Watershed sinh ra nhiu ng bin
sai (oversegmentation)
65
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)
66
TCH VNG DA THEO MU
title(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)
67
TCH VNG DA THEO MU
title('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');

68
TCH VNG DA THEO MU
//Phm Hong Giang
#include<highgui.h>
#include<cv.h>
#include<iostream>
usingnamespace 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<<"Dang tim mau do...\n";
for(int i=0;i<(src->height);i++)//Trong mang 2 chieu cua hinh anh..Chay tu 0 den
height cua anh

69
TCH VNG DA THEO MU
{
for(int j=0;j<(src->width);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]<50)&&(s.val[0]<50))
{
c.val[2]=250;//Gan gia tri kenh R ve 250
c.val[1]=50;//Gan gia tri kenh G len 50
c.val[0]=50;//Gan gia tri kenh B ve 50
cvSet2D(copy,i,j,c); //Thay doi gia tri cua diem anh va gan cho anh coppy
(G=255 R=0 B=0)
}
else//Gan toan bo diem anh con lai cua anh coppy thanh mau trang
70
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<<"So diem do tim thay la"<<num_red<<endl;
cvNamedWindow( "Input", CV_WINDOW_AUTOSIZE ); //Tao mot cua so Input
cvShowImage( "Input", src ); //Hien thi anh src trong cua so Input
cvNamedWindow( "Output", CV_WINDOW_AUTOSIZE );//Tao mot cua soOutput
cvShowImage( "Output", copy );
71
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 10ms
cvReleaseImage( &src );
cvReleaseImage( &copy );
cvReleaseImage( &tmp_img );
return 0;
}

72
TCH VNG DA THEO MU
73
TCH VNG DA THEO MU
74
TCH VNG DA THEO MU
75
MT S HM OPENCV
Tm trng tm mt vng
use 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 image is 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 moment
If 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.
76
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, int x_order, int y_order)
Retrieve calculated spacial moments from ptr memory block
Arguments -
CvMoments* ptr - pointer to allocated memory block which store all moments
int x_order - order of x (>=0)
int y_order - order of y (>=0)
e.g. -
cvGetSpatialMoment(moments, 1, 0) retrieves 1st order spacial moment around
x-axis
cvGetSpatialMoment(moments, 0, 1) retrieves 1st order spacial moment around
y-axis


77
Tm trng tm mt vng

-cvGetCentralMoment ( CvMoments* ptr, int x_order, int y_order )
Retrieve calculated central moments from ptr memory block
Arguments -
CvMoments* ptr - pointer to allocated memory block which store all moments
int x_order - order of x (>=0)
int y_order - order of y (>=0)
e.g. - cvGetCentralMoment(moments, 0, 0) retrieves 0th order central moment
cvLine (CvArr* img, CvPoint pt1, CvPoint pt2, CvScalar color, int thickness=1)
Draw a line between 2 points, pt1 and pt2
Arguments -
CvArr* img - source image
CvPoint pt1 - starting point of the line
CvPoint pt2 - ending point of the line
CvScalar color - color of the line (in the Blue, Green, Red order)
int thickness - thickness of the line in pixels

78
TCH VNG NH GiA HAI MC
cvInRangeS
Checks that array elements lie between two scalars.
void cvInRangeS(const CvArr src, CvScalar lower, CvScalar upper, CvArr dst);
src The first source array
lower The inclusive lower boundary
upper The exclusive upper boundary
dst The destination array, must have 8u or 8s type, binary
The function does the range check for every element of the input array:
79
Object Detection & Tracking using Color

Simple Example of Detecting Red objects
In this example, I am going to convert a video into a binary image based on the red
color. (Red color area of the video is assined to '1' and other area is assigned to '0' in
the binary image)

#include "stdafx.h
#include <cv.h>
#include <highgui.h>
//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;
}


80
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 using Gaussian kernel

81
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 using Gaussian kernel

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;
}


82
Object Detection & Tracking using Color
cvDestroyAllWindows() ;
cvReleaseCapture(&capture);
return 0;
}
83
PHN BIT HNH DNG DNG CONTOUR
Using 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
for quadrilaterals. 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, equilateral and etc by calculating and comparing
distances between vertices.

84
PHN BIT HNH DNG DNG CONTOUR
Well draw a line along the perimeter of every identified
polygon with colors blue for triangle, green
for quadrilaterals and red for heptagons.
cvFindContours( CvArr* img, CvMemStorage* str, CvSeq** first_contour,
int header_size, int mode, int method, CvPoint offset )
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 contours
CvSeq** first_contour - store a pointer to the first contour in the memory
block, 'str'
int header_size - size of the sequence header
int mode - mode of retrieval of contours from the image

85
PHN BIT HNH DNG DNG CONTOUR
You have to choose one of the following
CV_RETR_LIST - Retrieves all of the contours and put them in a list
CV_RETR_EXTERNAL - Retrieves only the extreme outer contours
CV_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 holes
CV_RETR_TREE - Retrieves all of the contours and reconstructs the
full hierarchy of nested contours
int method - Approximation method
You have to choose one of the following
CV_CHAIN_CODE - Outputs contours in the Freeman chain code
CV_CHAIN_APPROX_NONE - Translates all of the points from the
chain code into points
CV_CHAIN_APPROX_SIMPLE - Compresses horizontal, vertical,
and diagonal segments and leaves only their end points

86
PHN BIT HNH DNG DNG
CONTOUR
CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_K
COS - 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.
CvPoint offset - 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, int header_size,
CvMemStorage* storage, int method, double para1, int para2 )
Approximate polygonal curves with specified precision
arguments -
const void* src - Sequence of points
int header_size - size of the sequence header
CvMemStorage* storage - memory block that contains all contours


87
PHN BIT HNH DNG DNG
CONTOUR
int method - Approximation method. (The only method, available to
use for this argument is 'CV_POLY_APPROX_DP')
double para1 - approximation accuracy
int para2 - Determines whether the single sequence should be
approximated or all sequences in the same level or below
cvGetSeqElem( const CvSeq* seq, int index )
Returns a pointer to the element of 'seq' at 'index
cvReleaseMemStorage( CvMemStorage** storage )
Deallocate memory blocks which have been allocated by
'cvCreateMemStorage()' function
cvCreateMemStorage(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)


88
PHN BIT HNH DNG DNG
CONTOUR
cvContourArea(const CvArr* contour, CvSlice slice)
Calculate the area enclosed by sequence of contour points.
const CvArr* contour - array of vertices of the contour
CvSlice slice - starting and ending point of the contour.
'CV_WHOLE_SEQ' will take the whole contour to calculate the area
The 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)
This function returns the absolute value of any floating point number. ( This is
a C function, not a OpenCV function)
89
PHN BIT HNH DNG DNG
CONTOUR
int 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));
90
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 vertices in the contour(It should be a triangle)
if(result->total==3 )
{
//iterating through each point
CvPoint *pt[3];
for(int i=0;i<3;i++){
pt[i] = (CvPoint*)cvGetSeqElem(result, i);
}
//drawing lines around the triangle
cvLine(img, *pt[0], *pt[1], cvScalar(255,0,0),4);
cvLine(img, *pt[1], *pt[2], cvScalar(255,0,0),4);
cvLine(img, *pt[2], *pt[0], cvScalar(255,0,0),4);

}


91
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<4;i++){
pt[i] = (CvPoint*)cvGetSeqElem(result, i);
}

//drawing lines around the quadrilateral
cvLine(img, *pt[0], *pt[1], cvScalar(0,255,0),4);
cvLine(img, *pt[1], *pt[2], cvScalar(0,255,0),4);
cvLine(img, *pt[2], *pt[3], cvScalar(0,255,0),4);
cvLine(img, *pt[3], *pt[0], cvScalar(0,255,0),4);
}
92
PHN BIT HNH DNG DNG
CONTOUR
//if there are 7 vertices in the contour(It should be a heptagon)
else if(result->total ==7 )
{
//iterating through each point
CvPoint *pt[7];
for(int i=0;i<7;i++){
pt[i] = (CvPoint*)cvGetSeqElem(result, i);
}
//drawing lines around the heptagon
cvLine(img, *pt[0], *pt[1], cvScalar(0,0,255),4);
cvLine(img, *pt[1], *pt[2], cvScalar(0,0,255),4);
cvLine(img, *pt[2], *pt[3], cvScalar(0,0,255),4);
cvLine(img, *pt[3], *pt[4], cvScalar(0,0,255),4);
cvLine(img, *pt[4], *pt[5], cvScalar(0,0,255),4);
cvLine(img, *pt[5], *pt[6], cvScalar(0,0,255),4);
cvLine(img, *pt[6], *pt[0], cvScalar(0,0,255),4);
}
93
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;
}
94
PHN BIT HNH DNG DNG CONTOUR
95
PHN BIT HNH DNG MU DNG CONTOUR
96
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);
97
//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_BINAR
Y_INV);

cvNamedWindow("Thresholded Image");
cvShowImage("Thresholded Image",imgGrayScale);
98
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);
99
//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;i<3;i++){
pt[i] = (CvPoint*)cvGetSeqElem(result, i);
}
//drawing lines around the triangle
cvLine(img, *pt[0], *pt[1], cvScalar(255,0,0),4);
cvLine(img, *pt[1], *pt[2], cvScalar(255,0,0),4);
cvLine(img, *pt[2], *pt[0], cvScalar(255,0,0),4);
}
//obtain the next contour
contour = contour->h_next;
}
100
//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;
}

101
102
Tracking two Triangles in a Video

103

You might also like