1

im working on this assignment and for some reason its not copying all the rows. It skips certain lines of the bmp so it does not enlarge the picture entirely. I would greatly appreciate some feedback as to why its doing this. I know it's got to be related with the pointer arithmetic.

int enlarge(PIXEL* original, int rows, int cols, int scale, 
        PIXEL** new, int* newrows, int* newcols) 
{
    *newcols = cols * scale;
    *newrows = rows * scale;


    /* Allocate memory for enlarged bmp */ 
    *new = (PIXEL*)malloc( (*newrows)*(*newcols) * sizeof(PIXEL));
    if(!*new)
    {
        free(*new);
        fprintf(stderr, "Could not allocate memory.\n");
        return 1;
    }

    int i,j,k,l;
    int index = 0;
    int counter = scale*rows;
    PIXEL* o;
    PIXEL* n;


    for(i = 0; i < rows; i++)
    {
        for(j = 0; j < cols; j++)
        {

            for(k = 0; k < scale; k++)
            {

                o = original + (i*cols) + j;
                index++;
                for(l = 0; l < scale; l++)
                {
                    n = (*new) + ( i*cols*scale ) + index + (counter*l);
                    *n = *o;
                }

            }
        }
    }

    return 0;
}
4

1 回答 1

1

您正在将一个正方形像素块复制到您的整数缩放图像中。外部两个循环和您对原始像素地址的计算都很好。

现在,看看内部的两个循环,你会遇到这种奇怪的事情,counter而且index这不太合理。让我们重写它。您需要做的就是为每一行复制一组像素。

o = original + i*cols + j;
n = *new + (i*cols + j) * scale;

for(sy = 0; sy < scale; sy++)
{
    for(sx = 0; sx < scale; sx++)
    {
        n[sy*cols*scale + sx] = *o;
    }
}

我真的不喜欢i, j,k和等变量l。它很懒惰,没有任何意义。很难看出k是行索引还是列索引。所以我用sxandsy来表示“缩放的 x 和 y 坐标”(我建议使用xandy而不是jandi但我将它们保留原样)。


现在,这里有一个更好的方法。复制扫描线中的像素,而不是跳来跳去编写单个缩放块。在这里,您缩放单行,并多次执行此操作。你可以用这个替换你的四个循环:

int srows = rows * scale;
int scols = cols * scale;

for( sy = 0; sy < srows; sy++ )
{
    y = sy / scale;
    o = original + y * cols;
    n = *new + sy * scols;

    for( x = 0; x < cols; x++ ) {
        for( i = 0; i < scale; i++ ) {
            *n++ = *o;
        }
        *o++;
    }
}
于 2013-10-23T22:19:20.113 回答