我正在尝试构建一个四叉树,并且遇到一些困难。它旨在读取二进制图像(在别处处理)并执行各种操作。但是,当然,首先必须构造四元树。我希望继续细分树,直到所有像素都是一种纯色(黑色或白色),以方便操作。
我有以下函数,它只是调用一个辅助函数来处理构建树的冗长递归过程。
void Quadtree::constructQuadtree(Image* mImage){
if (mImage->imgPixels == 0) {
return;
}
root = new QTNode();
this->root = buildQTRecur(mImage, 0, 0, mImage->rows);
}
这是处理大量树构建的辅助函数:
QTNode* Quadtree::buildQTRecur(Image* mImage, int startRow, int startCol, int subImageDim) {
if (this->root == NULL) {
return this->root;
}
if (subImageDim >= 1) {
int initialValue = 0;
bool uniform = false;
// Check to see if subsquare is uniformly black or white (or grey)
for (int i = startRow; i < startRow + subImageDim; i++)
{
for (int j = startCol; j < startCol + subImageDim; j++)
{
if ((i == startRow) && (j == startCol))
initialValue = mImage->imgPixels[i*mImage->rows+j];
else {
if (mImage->imgPixels[i*(mImage->rows)+j] != initialValue) {
uniform = true;
break;
}
}
}
}
// Is uniform
if (uniform) {
this->root->value = initialValue;
this->root->NW = NULL;
this->root->SE = NULL;
this->root->SW = NULL;
this->root->NE = NULL;
return this->root;
}
else { // Division required - not uniform
this->root->value = 2; //Grey node
this->root->NW = new QTNode();
this->root->NE = new QTNode();
this->root->SE = new QTNode();
this->root->SW = new QTNode();
// Recursively split up subsquare into four smaller subsquares with dimensions half that of the original.
this->root->NW = buildQTRecur(mImage, startRow, startCol, subImageDim/2);
this->root->NE = buildQTRecur(mImage, startRow, startCol+subImageDim/2, subImageDim/2);
this->root->SW = buildQTRecur(mImage, startRow+subImageDim/2, startCol, subImageDim/2);
this->root->SE = buildQTRecur(mImage, startRow+subImageDim/2, startCol+subImageDim/2, subImageDim/2);
}
}
return this->root;
}
当我尝试运行它时,我陷入无限循环。如果有任何其他信息(如我的节点构造函数)或任何其他信息可以帮助我们,请告诉我们。
谢谢。
答案 0 :(得分:0)
我在您的代码中看到了几个问题:
谁负责创建子节点?如果你写两个
this->root->NW = new QTNode();
this->root->NW = buildQTRecur(mImage, startRow, startCol, subImageDim/2);
然后你fisrt分配一个新的四叉树,然后覆盖它。
你得到了计算均匀反转的逻辑。
break
。但它只能走出内循环。你应该考虑将它放在一个辅助函数中,并在这里做一个return
以立即退出这两个循环。出于效率原因你不应该写
if ((i == startRow) && (j == startCol))
initialValue = mImage->imgPixels[i*mImage->rows+j];
刚刚放
initialValue = mImage->imgPixels[startRow*mImage->rows+startCol];
循环前的