【问题标题】:Flatindexed 2D array - flipping an image vertically/horizontallyFlatindexed 2D 数组 - 垂直/水平翻转图像
【发布时间】:2016-07-17 18:28:53
【问题描述】:

我写了一些代码来尝试回答这个问题。

我得到了一个程序来绘制一个使用 X11 进行灰度缩放的图像。

有人要求我编写一个函数来水平/垂直翻转图像。

这是我的代码 sn-p

// flip the image, left-to-right, like in a mirror.
void flip_horizontal( uint8_t array[], 
              unsigned int cols, 
              unsigned int rows )
{

  int i;
  int j;
  for (i=0; i<rows;i++)
  {
    for (j=0; j<cols;j++)
      {
       array[rows*i+j]=array[rows*i+(cols-1-j)];
      }
  }
}

// flip the image top-to-bottom.
void flip_vertical( uint8_t array[], 
            unsigned int cols, 
            unsigned int rows )
{

int i=0;
int j=0;
  for (i=0; i<rows;i++)
  {
    for (j=0; j<cols;j++)
      {
       array[rows*i+j]=array[rows*(rows-1-i)+j];
      }
  }
  return;
}

我遇到的问题是我的水平函数仅将图像翻转一半,另一半保留其原始值。

我的垂直翻转功能也是一团糟,生成的图像根本不像它应该的那样,所以我试图调试我在编写函数的逻辑中犯了错误的地方。

我正在使用平面索引方法来访问二维数组值。

【问题讨论】:

  • 在 C 中 = 并不意味着“交换”。即使是这样,你还是发出了经典的“单词反转”咆哮,交换字母并再次交换它们。
  • 平面索引:array[rows*i+j] --> array[cols*i+j]

标签: c image 2d


【解决方案1】:

在您的水平翻​​转中,内部循环遍历所有列并为像素分配其镜像值。假设你最左边的像素是 100,最右边的像素是 23。一步之后,最左边的像素变成 23。现在,当涉及到最右边的像素时,它会尝试查看最左边的像素,中提琴,你又得到了 23。值 100 已经丢失。这就是为什么你的右半边图像不会改变。

垂直翻转同样的问题。

还有索引问题。我假设 cols 表示列数,rows 表示行数。假设图像是按行存储的,这意味着平面数组中的布局是逐行的,就像我们的阅读顺序一样,那么第 i 行第 j 列的像素位于索引 cols*i+j , 而不是 rows*i+j。不直观,cols 是列数,同时也是行的大小。调试愉快:)

【讨论】:

    【解决方案2】:
    static uint8_t temp;
    
    void flip_horizontal( uint8_t array[], 
                  unsigned int cols, 
                  unsigned int rows )
    {
    
      int i;
      int j;
      for (i=0; i<rows/2;i++)
      {
        for (j=0; j<cols;j++)
          {
           temp=array[rows*i+j];
           array[rows*i+j]=array[rows*i+(cols-1-j)];
           array[rows*i+(cols-1-j)]=temp;
          }
      }
    }
    
    // flip the image top-to-bottom.
    void flip_vertical( uint8_t array[], 
                unsigned int cols, 
                unsigned int rows )
    {
    
    int i=0;
    int j=0;
      for (i=0; i<rows;i++)
      {
        for (j=0; j<cols/2;j++)
          {
           temp=array[rows*i+j];
           array[rows*i+j]=array[rows*(rows-1-i)+j];
           array[rows*(rows-1-i)+j]=temp;
          }
      }
      return;
    }
    

    这段代码可以大大提高效率,但基本上我所做的是将你进行交换操作的次数减半,并且我引入了一个临时变量来在交换操作期间保存数据。

    【讨论】:

    • 您还没有更正平面索引错误:array[rows*i+j] --> array[cols*i+j]
    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 2016-07-29
    • 2015-12-28
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多