2013-07-22 61 views
0

我正在嘗試構建一個四叉樹,並且遇到了一些困難。它旨在讀取二進制映像(在別處處理)並執行各種操作。但是,當然,首先必須構建四叉樹。爲了便於操作,我希望繼續細分樹,直到所有像素都是單色(黑色或白色)。無法構建四叉樹?

我有以下函數,它只是簡單地調用一個幫助函數來處理構建樹的冗長的遞歸過程。

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

    那麼你可以先分配一個新的四叉樹,然後覆蓋它。

  • 你得到邏輯來計算統一扭轉。

  • 如果你發現兩個不同的像素,那麼你做一個break。但它只是走出內在循環。你應該考慮把它放在一個輔助函數中,並且在這裏做一個return以便一次擺脫兩個循環。
  • 效率的原因,你不應該寫

    if ((i == startRow) && (j == startCol)) 
        initialValue = mImage->imgPixels[i*mImage->rows+j]; 
    

    只要把

    initialValue = mImage->imgPixels[startRow*mImage->rows+startCol]; 
    

    循環