【问题标题】:Find the average colour on screen in SDL在 SDL 中查找屏幕上的平均颜色
【发布时间】:2021-10-22 11:19:30
【问题描述】:

在 SDL 中,我们试图找到屏幕的平均颜色。为此,我们正在读取所有像素颜色值并将它们放入一个数组中(性能无关紧要),但是由于某种原因,GetPixel 总是返回颜色 (0,0,0,0)。我已经确定 RenderReadPixels 可以正常工作,因为保存屏幕截图可以正常工作。

const Uint32 format = SDL_PIXELFORMAT_ARGB8888;
SDL_Surface* surface = SDL_CreateRGBSurfaceWithFormat(0, width, height, 32, format); 
SDL_RenderReadPixels(renderer, NULL, format, surface->pixels, surface->pitch);

float* coverage = new float[width*height]; // * allocates memory
coverage[0] = 1;

for (int i = 0; i < width; i++)
{       
    for (int j = 0; j < height; j++)
    {          
        SDL_Color col;
        col = GetPixel(surface, i, j);
        coverage[i * height + j] = (1/3)(col.r + col.b + col.g); //Return coverage value at i, j
        std::cout << coverage[i * height + j];  //Always returns 0
        std::cout << "\n";
    }
}

SDL_Color GetPixel(SDL_Surface* srf, int x, int y)
{
    SDL_Color color;

    SDL_GetRGBA(get_pixel32(srf, x, y), srf->format, &color.r, &color.g, &color.b, &color.a);

    return color;
}
Uint32 get_pixel32(SDL_Surface* surface, int x, int y)
{
    //Convert the pixels to 32 bit
    Uint32* pixels = (Uint32*)surface->pixels;

    //Get the requested pixel
    return pixels[(y * surface->w) + x];
}
    

【问题讨论】:

  • 1/3int 上下文中为 0。

标签: c++ sdl-2


【解决方案1】:

1/3 始终为 0,因为数字提升在 C++ 中的工作方式。

最好明确说明你想要什么:

coverage[i * height + j] = float(col.r + col.b + col.g) / 3.0;

【讨论】:

  • 这会执行double 除法,这可能是无意的。
  • 你能解释一下吗?如果我在 Godbolt 中输入 float f(int x) { return float(x) / 3.0; },我只会看到单精度指令
  • 有趣。 GCC 确实输出了一个浮点除法。 Clang 默认进行双重除法,并进行优化浮动。 MSVC 似乎总是做双重除法。在任何情况下,该表达式的 decltype 是双精度的,真正的浮点除法将是 / 3.0f
猜你喜欢
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 2013-12-20
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多