最近在做一个Motion Detection的课题,在课题中提取的运动物体往往由离散的点组成,如果要用连通分量的计算方法提取每个运动物体的轮廓不太容易,为此要将由离散点组成的图像进行膨胀,腐蚀运算。
膨胀 dilation
考虑两幅二值图像A,B。它们的前景用黑色,背景用白色。另fA和fB表示各自前景点的集合。定义膨胀运算为:dilation(A,B) = {a+b| a∈A,b∈B}。比如:
A = {(2,8),(3,6),(4,4),(5,6),(6,4),(7,6),(8,8)}
B = {(0,0),(0,1)}
dilation(A,B) = {(2,8),(2,9),(3,6),(3,7),(4,4),(4,5),(5,6),(5,7),(6,4),(6,5),(7,6),(7,7),(8,8),(8,9)}
腐蚀 erosion
同样考虑两幅图像A,B。定义腐蚀运算为: erosion(A,B) = {a|(a+b)∈A, a∈A,b∈B}
膨胀腐蚀运算的性质
•交换律 dilation(A,B) = dilation(B,A)
•结合律 dilation(dilation(A,B),C) = dilation(A,dilation(B,C))
•并集 dilation(A,B∪C) = dilation(A,B)∪dilation(A,C)
•增长性 if A blongs to B then dilation(A,K) blongs to dilation(B,K)
C++ 实现
这里 buf 相当于 A,model相当于B 计算dilation(buf,model)
void ShapeOper::dilation(unsigned char* buf, int width, int height, vector<point> model)
{
int i,j,k;
point P;
unsigned char* temp = new unsigned char[width*height];
memcpy(temp,buf,width*height);
for(i=0;i<height;i++){
for(j=0;j<width;j++){
if(temp[(i*width+j)] < 10){
for(k=0;k<model.size();k++){
P.x = i + model[k].x; //Dilation Operation 求取并集
P.y = j + model[k].y;
if(P.x>=0 && P.x<width && P.y>=0 && P.y<height){
buf[(P.x*width+P.y)] = 0;
}
}
}
}
}
if(temp!=NULL){
delete[] temp;
}
}
计算erosion(buf,model)
void ShapeOper::erosion(unsigned char* buf, int width, int height, vector<point> model)
{
int i,j,k;
point P;
unsigned char* temp = new unsigned char[width*height];
memcpy(temp,buf,width*height);
bool is_point = true;
for(i=0;i<height;i++){
for(j=0;j<width;j++){
if(temp[(i*width+j)] < 10){
is_point = true;
for(k=0;k<model.size();k++){
P.x = i + model[k].x;
P.y = j + model[k].y;
if(P.x>=0 && P.x<width && P.y>=0 && P.y<height){
if(temp[(P.x*width+P.y)] > 10){
is_point = false;
//cout<<"other"<<endl;
break;
}
}
}
if(is_point){
buf[(i*width+j)] = 0;
}
}
}
}
if(temp!=NULL){
delete[] temp;
}
}
本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/xlvector/archive/2006/01/26/588828.aspx