2017-12-18 328 views
0

我试图将像素逐像素旋转90度,似乎有一个数学问题,我无法弄清楚......和数组越界异常 here是我尝试顺时针旋转90度的图像

const unsigned char *srcData = source.getData(); 
unsigned char *dstData = new unsigned char[width * height * bpp]; 


size_t srcPitch = source.getRowSpan(); 
    size_t dstPitch = width * bpp; 

    for(int i=0; i<height; i++) 
    { 
     for(int j=0; j<width * bpp; j++) 
     { 
      rotatedData[(i * dstPitch) + j]= dstData[(height-i) * dstPitch + j]; 
     } 
    } 
+2

'*'具有(在数学和C++相同)比'-'优先级数字 – user463035818

+0

仍具有一定界限dstData [I + J *宽度* BPP] = srcData [(宽×BPP)* J + 1 - j]; –

+0

你已经有了dstPitch,不知道你为什么没有在你的条件中使用它作为inner for循环。 – Eddge

回答

1

首先,让我们构建一个图像描述符来跟踪尺寸。

struct ImageDescriptor { 
    std::size_t width; 
    std::size_t height; 
    std::size_t channels; 

    std::size_t stride() const { return width * channels; } 
    std::size_t offset(std::size_t row, std::size_t col, std::size_t chan) { 
    assert(0 <= row && row < height); 
    assert(0 <= col && col < width); 
    assert(0 <= chan && chan < channels); 
    return row*stride() + col*channels + chan; 
    // or, depending on your coordinate system ... 
    // return (height - row - 1)*stride() + col*channels + chan; 
    } 
    std::size_t size() const { return height * stride(); } 
}; 

现在我们需要两个ImageDescriptors来跟踪我们两幅图像的尺寸。请注意,除非原始图像是正方形,否则旋转后的图像将具有不同的宽度和高度(从而步幅)。具体来说,旋转图像的宽度将是源图像的高度(反之亦然)。

const ImageDescriptor source(width, height, bpp); 
ImageDescriptor target(height, width, bpp); // note width/height swap 

执行转换的常用方法是循环搜索目标像素并查找源像素。

unsigned char *rotated = new[target.size()]; 

for (std::size_t row = 0; row < target.height; ++row) { 
    for (std::size_t col = 0; col < target.width; ++col) { 
    for (std::size_t chan = 0; chan < target.channels; ++chan) { 
     rotated[target.offset(row, col, chan)] = 
      original[source.offset(col, row, chan)]; 
    } 
    } 
} 

一旦你做对了,你可以努力消除不必要的计算。第一个机会就是通过目标图像,因为所有内容都是按照内存顺序。第二个机会是,将通道回路中的源偏移计算提升出来。最后,如果bpp是常量,则可以展开最内层的循环。

unsigned char *p = rotated; 
for (std::size_t row = 0; row < target.height; ++row) { 
    for (std::size_t col = 0; col < target.width; ++col) { 
    const std::size_t base = source.offset(col, row, 0); 
    for (std::size_t chan = 0; chan < target.channels; ++chan) { 
     *p++ = original[base + chan]; 
    } 
    } 
} 
+0

非常感谢您的回答。但我仍然得到扫描图像 –

+0

@ahmed安德烈:我不知道你是什么意思的“扫描图像”。 –

0

试试这个:

for (int j = 0; j<width * bpp; j++) 
    { 
     for (int i = 0 ; i<height; i++) 
     { 
      rotatedData[(height)*(dstPitch - j - 1) + i] = dstData[(i * dstPitch) + j]; 
     } 
    } 

,如果dstData没有平方:

//define rotatedData_height before. 
    rotatedData[(rotatedData_height)*(dstPitch - j - 1) + i] = dstData[(i * dstPitch) + j]; 
+0

我试过了,但我得到scanlines ..似乎它不能正常工作 –

+0

你可以显示你如何迭代for循环? –

+0

@ahmedandre添加了for循环。 – ariaman5