【问题标题】:Don't understand how this code is scaling a bmp image不明白这段代码如何缩放 bmp 图像
【发布时间】:2017-04-02 00:42:03
【问题描述】:

以下代码是我的导师给我的。我只是不明白这是如何缩放 bmp 图像。我知道有关 bmp 图像的基础知识(维基百科上的信息)。我知道这种方法应该将新图像的行和列乘以任何比例。我试图手动运行代码,但它让我更加困惑。任何帮助都感激不尽。谢谢!

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

    //memory allocated for enlaged bmp 
    *new = (PIXEL*)malloc(*newrows * *newcols * sizeof(PIXEL));

    int row, col, sx, sy;


    //transverse through every row 
    for (row = 0; row < rows; row++ )
    //transvere through every col  
    for (col = 0; col < cols; col++ ){
        //im unsure what this is for 
        PIXEL* o = original + (row * cols) + col;
    for(sy = 0; sy < scale; sy++ )
    for(sx = 0; sx < scale; sx++ )
          { 
              //im unsure what this is for 
              PIXEL* n = *new + (scale * row) * *newcols + (scale * col) + (sy * *newcols) + sx;
              *n = *o;
          }
    }
    return 0; 
}

这是 PIXEL 的结构。

typedef struct {
  unsigned char r;
  unsigned char g;
  unsigned char b;
} PIXEL;

还有其他代码,但我认为这个问题不需要。

【问题讨论】:

  • 内部的两个循环用o 指向的像素副本填充放大版本中的一个正方形。 o 只是您在所有像素上循环的上下文中的“当前像素”。
  • 每个像素的作用是什么?

标签: c bmp


【解决方案1】:
    PIXEL* o = original + (row * cols) + col;

在这里,他正在检索指向原始图像中源像素的指针;它只是简单的指针运算,基于位图中的行在内存中是连续的这一事实。一般来说,在 C 样式矩阵 width-wide 中,元素 (x, y) 的地址是 beginning + (y * width) + x

然后,他循环遍历目标图像中的一个正方形scale x scale

for(sy = 0; sy < scale; sy++ )
for(sx = 0; sx < scale; sx++ )
      { 
          //im unsure what this is for 
          PIXEL* n = *new + (scale * row) * *newcols + (scale * col) + (sy * *newcols) + sx;

n 指针指向目标图像中的目标像素;如果您从源图像中匹配上面的公式并重新排列一些术语,您会看到他正在访问新图像,位置

(scale * col + sx, scale * row + sy)

(请记住,新图像是*newcols 宽)。

          *n = *o;

这里他只是将源像素复制到目标像素。

在实践中,他将每个源像素“扩展”为目标图像中的 scale x scale 正方形。

【讨论】:

  • 这是一个很好的解释。非常感谢!
猜你喜欢
  • 2012-09-01
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2014-04-11
相关资源
最近更新 更多