2014-10-07 111 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

但它不是唯一的错!我只会在这里概述它,因为它会重写一遍。

您复制“行*列” 连续,也就是开始在左上角,继续右下角:

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

,但你必须将每列(或行)独立地:

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