0

我编写了这个我想在程序中使用的函数,但由于某种原因,尽管没有出错,但它还是失败了:

std::deque <std::deque <bool> > load_image(std::string & image_name){
    SDL_Surface * image = open_image(image_name);
    if (!image)
        exit(3);
    Uint32 * pixels = (Uint32 *) image -> pixels;
    std::deque <std::deque <bool> > grid(HEIGHT, std::deque <bool>(WIDTH, false));
    for(int y = 0; y < std::min(image -> h, HEIGHT); y++)
        for(int x = 0; x < std::min(image -> w, WIDTH); x++)
            grid[y][x] = (pixels[(image -> w * y) + x] == 0);
    SDL_FreeSurface(image);
    return grid;
}

我只是试图将像素是否为黑色复制到grid. 当我单独运行时grid[y][x](pixels[(image -> w * y) + x] == 0)程序运行良好。当我这样做grid[y][x] = (pixels[(image -> w * y) + x] == 0);时,程序会在图像中间的某个地方崩溃。

我很确定(image -> w * y) + x得到了正确的像素,无论如何x,并且y仅限于,所以我没有看到什么?

4

1 回答 1

2

程序在图像中间的某个地方崩溃。

您忘记提及它是否会导致读取或写入内存崩溃。您也可以尝试调试它 - 通过 VisualStudio/gdb 或将y和的值转储xstderr/OutputDebugString中。

网格[y][x] = (像素[(图像 -> w * y) + x] == 0);

没有。

要解决单像素使用问题:

&((const char*)image->pixels)[y * image->pitch + x*image->format->BytesPerPixel];

或者

(const Uint32*)((const char*)image->pixels + y * image->pitch + x*image->format->BytesPerPixel)

像素不保证为 32 位。此外,如果这不是软件界面,您需要将其锁定。请参阅SDL_SurfaceSDL_PixelFormat的文档

于 2012-01-17T22:23:08.603 回答