垂直翻转图像

Flip an image vertically

本文关键字:图像 垂直翻转      更新时间:2023-10-16

在从openGL检索缓冲区后,我正在尝试垂直翻转图像。它似乎输出了一个错误的图像,代码如下:

const int width = 100;
const int height = width;
const int components = 3;
unsigned char pixels[width * height * components];
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
unsigned char flipPixels[width * height * components];
for (int i = 0; i < width; ++i) {
    for (int j = 0; j < height; ++j) {
        for (int k = 0; k < components; ++k) {
            flipPixels[i + j * width + k] = pixels[(height) * (width) - ((j+1) * width) + i + k];
        }
    }
}

我知道我只能迭代一半的高度并实现相同的高度,但我想通过遍历图像的完整高度来实现它。我似乎搞不清代码出了什么问题。如有任何帮助,我们将不胜感激。

我不确定图像是如何存储的,但您的索引ik的步幅相同,这是可疑的。也许你想要i * componentsj * width * components。之后,垂直反转只需将j更改为(height - j - 1)即可。

flipPixels[(i + j * width) * components + k] = pixels[(i + (height - 1 - j) * width) * components + k];

我遇到了同样的问题,OpenGL返回的像素导致了一个倒置的位图。所以我这样翻转它们:但位图仍然从左向右翻转。。。

void Flip(GLubyte* pixels, int pixelbuffersize)
{
    // basically rewrites from bottom up...
    std::vector<GLubyte> flipped_pixels(pixels, pixels+pixelbuffersize);
    auto count = flipped_pixels.size();
    std::reverse(flipped_pixels.begin(), flipped_pixels.end());
    GLubyte* buff = (reinterpret_cast<GLubyte*>(&flipped_pixels[0]));
    const void * pnewdata = (const void *)buff;
    memcpy(pixels, pnewdata, count);
}

使用std::copymemcpy 更有效地复制整行像素

使用C++std::copy:

for (size_t r = 0; r < height; r++) {
    auto src = &pixels[r*components*width];
    auto dst = &flipPixels[(height - r - 1)*components*width];
    std::copy(src, src + components*width, dst);
}

使用C memcpy:

for (int r = 0; r < height; r++) {
    unsigned char *src = &pixels[r*components*width];
    unsigned char *dst = &flipPixels[(height - r - 1)*components*width];
    memcpy(dst, src, components*width);
}

注意事项:这假设您在呼叫glReadPixels:

glPixelStorei(GL_PACK_ALIGNMENT, 1);

否则你可能会遇到一些填充/对齐问题。