CObjSet.cpp
#include "stdafx.h"
#include "CObjSet.h"
//test
void CCalObjectBox::Clear()
{
int i;
for (i = 0; i < m_objs.size(); i++)
{
CObjectSet *obj = m_objs.at(i);
delete obj;
}
m_objs.clear();
}
int CCalObjectBox::SetImage(cv::Mat *img)
{
if (img->channels() != 1)
return 0;
Clear();
m_obj = img;
return 1;
}
void CCalObjectBox::InsertClass(int index, int i, int j)
{
CObjectSet *obj = m_objs.at(index);
while (obj->m_link >= 0)
{
index = obj->m_link;
obj = m_objs.at(index);
}
obj->Insert(i, j);
}
int CCalObjectBox::combineClass(int index0, int index1)
{
CObjectSet *obj0 = m_objs.at(index0);
CObjectSet *obj1 = m_objs.at(index1);
while (obj0->m_link >= 0)
{
index0 = obj0->m_link;
obj0 = m_objs.at(index0);
}
while (obj1->m_link >= 0)
{
index1 = obj1->m_link;
obj1 = m_objs.at(index1);
}
if (obj0 == obj1)
return 0; // 已在一个类中
obj1->m_link = index0;
obj0->m_ptnum += obj1->m_ptnum;
obj0->m_box.AddBox(obj1->m_box);
return 1;
}
int CCalObjectBox::CalBox()
{
int i, j, k, width, height, size, count;
short *tag; // 存贮每个像素所在的等价类
unsigned char *ptr;
CObjectSet *obj;
if (m_obj == NULL)
return 0;
width = m_obj->cols;
height = m_obj->rows;
size = width * height;
tag = new short[size];
memset(tag, 0xff, size * sizeof(short));
k = 0;
int st;
for (j = 0; j < height; j++)
{
st = j * width;
for (i = 0; i < width; i++)
{
unsigned char ss = m_obj->at<unsigned char>(j, i);
if (ss < m_sill)
continue;
count = 0;
if (j > 0 && tag[st + i - width] >= 0)
{
tag[st + i] = tag[st + i - width];
count++;
}
if (i > 0 && tag[st + i - 1] >= 0)
{
tag[st + i] = tag[st + i - 1];
count++;
}
if (count == 0)
{
CObjectSet *obj = new CObjectSet;
int index = m_objs.size();
m_objs.push_back(obj);
tag[st + i] = index;
InsertClass(index, i, j);
continue;
}
if (count == 1 || (tag[st + i - 1] == tag[st + i - width]))
{
InsertClass(tag[st + i], i, j);
continue;
}
if (count == 2)
{
// 等价类需要合并
combineClass(tag[st + i - 1], tag[st + i - width]);
InsertClass(tag[st + i], i, j);
}
}
}
// 对每一个类,点数少的除掉,包围盒小的除掉,乘下的加入包围盒
vector<CObjectSet *