[英]Copying a region of pixels from an image
获取一个新图像,该图像是该区域的副本。 空区域将返回空指针。 如果内存分配失败,则返回空指针。 调用者负责释放返回的数组。
该区域包括从[left, right-1]
所有列,以及从[top, bottom-1]
起的所有行。
在每种情况下,您都可以假设left <= right
和top <= bottom
:不需要为此进行测试。
该区域的面积是(right-left) * (bottom-top)
像素,这意味着如果left == right
或top == bottom
,则该区域没有面积,并且被定义为“空”。 每个函数都记录了如何处理空白区域。
此解决方案在终端中引发一个错误,即“内存损坏”,它指向我的malloc函数调用,后跟0x00001dec880
行中的一个非常奇怪的数字,每次编译时该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;
}
此循环是错误的:
for(int i = corner1; i < corner2; i++) {
newimg[i] = array[i]; }
源和目的地的索引必须不同,因为它们的尺寸不同。 您可以这样做:
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
}
}
这个
for(int i = corner1; i < corner2; i++) {
newimg[i] = array[i]; }
从 array[i]
复制,这是您想要的,但是它也复制到相同位置的newimg
; 好像newimg
与array
一样大。 您需要从第0个索引开始复制到newimg
:
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
。
但这不是唯一的错误! 我只在这里概述它,因为它需要认真地重写。
您连续复制“行*列”,即从左上角开始,一直到右下角:
..........
..********
**********
******....
..........
但您必须独立复制每列(或行):
..........
..****....
..****....
..****....
..........
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.