c++ - 从图像中获取不正确的读数

标签 c++ pixel sdl-image

我制作了一个 3x3 的图像,所有方 block 都是黑色的 (0,0,0),除非角落...... 在我有红色、绿色、蓝色和白色像素的地方,如下图所示:

R, 0, G
0, 0, 0
B, 0, W

如果我理解正确的话,它应该作为 R, 0, G, 0, 0, 0, B, 0, W 放在像素数据数组中。 我遇到的问题是打印出来的是:

[255, 0, 0] [0, 0, 0]   [0, 0, 0]
[0, 0, 0]   [0, 0, 0]   [0, 0, 0]
[0, 0, 255] [0, 0, 255] [255, 0, 0]

这是我的代码:

Uint32 GetPixel(SDL_Surface *img, int x, int y) {
    //Convert the pixels to 32 bit
    Uint32 *pixels = (Uint32*)img->pixels;

    //Get the requested pixel
    Uint32 offsetY = y * img->w;
    Uint32 offsetPixel = offsetY + x;
    Uint32 pixel = pixels[offsetPixel];

    return pixel;
}



int main(int argc, char *argv[]) {
    printf("Hello world!\n");

    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface *img = IMG_Load("Images/Colors.png");
    vector <Uint32> pixels;

    SDL_LockSurface(img);

    for (int y = 0; y < img->h; y++) {
        Uint8 r, g, b;
        Uint32 pixel;
        for (int x = 0; x < img->w; x++) {
            pixel = GetPixel(img, x, y);

            SDL_GetRGB(pixel, img->format, &r, &g, &b);
            printf("[%u, %u, %u]\t", r, g, b);
            pixels.push_back(pixel);
        }
        printf("\n");
    }

    SDL_UnlockSurface(img);

system("pause");
return 0;
}

编辑:我的预期:

[255, 0, 0] [0, 0, 0]   [0, 255, 0]
[0, 0, 0]   [0, 0, 0]   [0, 0, 0]
[0, 0, 255] [0, 0, 0]   [255, 255, 255]

最佳答案

问题出在您的 GetPixel 函数中。尝试这样的事情:

Uint32 GetPixel(SDL_Surface *surface, int x, int y)
{
    int bpp = surface->format->BytesPerPixel;
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
    return *(Uint32*)p;
}

关于c++ - 从图像中获取不正确的读数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580501/

相关文章:

C++:库 SDL_image.h 中的奇怪错误 "expected initializer before extern"

c++ - [列表/vector ] : Need some foundation advice

Python:图像显示中的像素值?

css - 什么是 Android 设备独立像素?它与常规 css 像素有何不同?

android - 将SDL2扩展库添加到android项目中

sdl - SDL2 中的纹理渐变 - 使用 SDL_image

c++ - 两个宏的 C/C++ 幂

C++ 字符串对象数组的选择排序

c++ - 关于何时在 C++ 类中显式启用/禁用复制的指南?

c++ - OpenCV,将一 block 像素从图像映射到图像时的噪声