【问题标题】:Rotate pixel array 90 degrees in C++在 C++ 中将像素数组旋转 90 度
【发布时间】:2014-02-04 11:14:42
【问题描述】:

我编写了下一个函数来将一个无符号字符像素数组旋转 90 度,该数组包含一个 RGB 图像。我面临的问题是旋转后的输出完全是乱码。

void rotate90(unsigned char *buffer, const unsigned int width, const unsigned int height)
{
    const unsigned int sizeBuffer = width * height * 3; 
    unsigned char *tempBuffer = new unsigned char[sizeBuffer];

    for (int y = 0, destinationColumn = height - 1; y < height; ++y, --destinationColumn)
    {
        int offset = y * width;

        for (int x = 0; x < width; x++)
        {
            tempBuffer[(x * height) + destinationColumn] = buffer[offset + x];
        }
    }

    // Copy rotated pixels

    memcpy(buffer, tempBuffer, sizeBuffer);
    delete[] tempBuffer;
}

【问题讨论】:

  • 您是否尝试过使用小型阵列并手动计算出步骤?这将是调试此类问题的最佳方法。无论如何,由于您不知道是代码有问题还是实际逻辑有问题,所以这是一个很好的起点。
  • 好像一个像素用了3个字节。只体现在sizeBuffer的分配上,其他地方没有。

标签: c++ rotation pixels


【解决方案1】:

将最内层循环中的行替换为:

for (int i = 0; i < 3; i++)
    tempBuffer[(x * height + destinationColumn) * 3 + i] = buffer[(offset + x) * 3 + i];

【讨论】:

    【解决方案2】:

    这只是 C 语言,为临时 rgb 类型添加强制转换,让编译器处理像素复制和偏移计算:

    #include <algorithm>
    #include <memory>
    
    // buffer is interleaved RGB
    void rotate90( unsigned char *buffer, const unsigned int width, const unsigned int height ) {
        struct rgb { unsigned char r_, g_, b_; };
        static_assert( sizeof( rgb ) == 3, "?" );
    
        size_t const count { width * height };
    
        auto source = reinterpret_cast<rgb*>( buffer );
    
        auto dest = std::unique_ptr<rgb[]>( new rgb[ count ] );
    
        for ( size_t y {}, destinationColumn = height - 1; y < height; ++y, --destinationColumn ) {
            size_t offset = y * width;
            for ( size_t x {}; x < width; x++ )
                dest[ ( x * height ) + destinationColumn ] = source[ offset + x ];
        }
    
        // Copy rotated pixels
        std::copy_n( dest.get(), count, source );
    }
    

    您还应该在这里寻找有关如何在不临时存储和复制图像大小的情况下旋转 90 度的想法:http://en.wikipedia.org/wiki/In-place_matrix_transposition

    【讨论】:

      猜你喜欢
      • 2013-05-17
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 2013-10-27
      相关资源
      最近更新 更多