문제

I wrote this function that I want to use in a program, but for some reason, it fails despite nothing going wrong:

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;
}

I'm simply trying to copy whether or not the pixel is black into the grid. When I run grid[y][x] and (pixels[(image -> w * y) + x] == 0) separately, the program runs fine. When I do grid[y][x] = (pixels[(image -> w * y) + x] == 0);, the program crashes somewhere in the middle of the image.

I'm pretty sure (image -> w * y) + x gets the correct pixel, no matter what x and y are limited to, so what am I not seeing??

도움이 되었습니까?

해결책

the program crashes somewhere in the middle of the image.

You forgot to mention whether it crashes reading or writing memory. Also you could try debugging it - either via VisualStudio/gdb or by dumping values of y and x into stderr/OutputDebugString.

grid[y][x] = (pixels[(image -> w * y) + x] == 0);

Nope.

To address single pixel use:

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

or

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

Pixel is not guaranteed to be 32bit. Also, if this is not a software surface, you'll need to lock it. See documentation for SDL_Surface and SDL_PixelFormat

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top