2014-10-07 110 views
0

獲取作爲區域副本的新圖像。空白區域返回空指針 。如果內存分配失敗,則返回一個空指針 。調用者負責釋放返回的數組。複製圖像中的像素區域

該區域包括[left, right-1](包含)在內的所有列, 以及從[top, bottom-1](含)的所有行。

在任何情況下,您都可以假設left <= righttop <= bottom: 不需要爲此進行測試。

的區域的面積是(right-left) * (bottom-top)像素,這 意味着如果left == righttop == bottom,該區域不具有 區域並且被定義爲「空」。每個功能都注意如何處理空白區域。

此解決方案在終端中引發了一個稱爲「內存損壞」的錯誤,它指向我的malloc函數調用,然後沿着0x00001dec880的行輸入一個非常奇怪的數字,每次編譯時都會有所不同。我不知道這是爲什麼,並幫助將不勝感激

uint8_t* region_copy(const uint8_t array[], unsigned int cols, unsigned int rows, 
         unsigned int left, unsigned int top, unsigned int right, unsigned int bottom) { 

    unsigned int corner1 = left + (top*cols); 
    unsigned int corner2 = right + (bottom*cols); 
    unsigned int newsize = (right - left) * (bottom - top); 

    if(left==right || top == bottom) { 
     return NULL; 
    } 

    uint8_t* newimg = malloc(newsize * sizeof(uint8_t)); 

    if(newimg == NULL){ 
     return NULL; 
    } 

    memset(newimg, 0, newsize); 

    for(int i = corner1; i < corner2; i++) { 
     newimg[i] = array[i]; 
    } 

    return newimg; 
} 

回答

1

這個循環是錯誤的:

for(int i = corner1; i < corner2; i++) { 
    newimg[i] = array[i]; } 

源和目的地的指數需要是不同的,因爲它們的尺寸是不同的。你可以做soemthing這樣的:

for (int r = top; r < bottom; r++)    // for each source row 
{ 
    for (int c = left; c < right; c++)   // for each source col 
    { 
     int src_index = r * cols + c;   // calc source index in array[] 
     int dst_index = (r - top) * (right - left) + (c - left); 
               // calc dest index in newimg[] 
     newimg[dst_index] = array[src_index]; // copy src -> dest 
    } 
} 
1

for(int i = corner1; i < corner2; i++) { 
    newimg[i] = array[i]; } 

副本array[i],這是你想要的,但它也拷貝到newimg在相同的位置;就好像newimgarray一樣大。你需要複製到newimg開始在其第0指數:

for(int i = corner1; i < corner2; i++) { 
    newimg[i-corner1] = array[i]; } 

或更清晰的操作

for(int i = 0; i< corner2 - corner1; i++) { 
    newimg[i] = array[corner1 + i]; } 

它的「更清晰」,因爲那麼很明顯你複製corner2 - corner1元素,開始在corner1

但它不是唯一的錯!我只會在這裏概述它,因爲它會重寫一遍。

您複製「行*列」 連續,也就是開始在左上角,繼續右下角:

.......... 
..******** 
********** 
******.... 
.......... 

,但你必須將每列(或行)獨立地:

.......... 
..****.... 
..****.... 
..****.... 
..........