代码之家  ›  专栏  ›  技术社区  ›  Gediminas

将浮点的heightmap数组导出到16位原始

  •  2
  • Gediminas  · 技术社区  · 7 年前

    我有一个256x256的 float 代表高度图的。 我想把它导出为每像素16位的原始图像。正确的转换方法是什么 浮动 uint16_t . ( 我知道精度的损失 )

    void ExportHeightmap(const Vector<float>& rHeights)
    {
        std::vector<uint16_t> output(256 * 256);
    
        float min = std::numeric_limits<float>::max();
        float max = std::numeric_limits<float>::min();
    
        for (size_t i = 0; i < output.size(); ++i)
        {
            float f = rHeights[i];
    
            if (min > f) min = f;
            if (max < f) max = f;
    
            output[i] = static_cast<uint16_t>(rHeights[i]);
        }
    
        std::cout << " Min: " << min << std::endl; // -49.77
        std::cout << " Max: " << max << std::endl; // 357.84
    
        std::fstream file("Heightmap.raw", std::ios::out | std::ios::binary);
        file.write((char*)output.data(), output.size() * sizeof(uint16_t));
    }
    

    编辑:我的目标是将应用程序中生成的heightmap导出到图像中。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Scheff's Cat    7 年前

    uint16_t

    在这种情况下,将高度值移动并缩放到新范围,即缩放(max-min)->65535和translate min->0

    可能是这样的:

            value - min
    pixel = ----------- * 65535
             max - min
    

    在代码中:

    #include <cstdint>
    #include <iomanip>
    #include <iostream>
    
    std::uint16_t floatToUInt16(float value, float min, float max)
    {
      return (std::uint16_t)((value - min) / (max - min) * 65535.0f);
    }
    
    int main()
    {
      float min = -49.77f, max = 357.84f;
      // some test values
      float values[] = { 0.0f, min, max, min / 2, max / 2 };
      // test conversion
      for (float value : values) {
        std::cout << std::fixed << std::setw(10) << value
          << " -> "
          << std::setw(5) << floatToUInt16(value, min, max)
          << '\n';
      }
      return 0;
    }
    

    输出:

      0.000000 ->  8001
    -49.770000 ->     0
    357.839996 -> 65535
    -24.885000 ->  4000
    178.919998 -> 36768
    

    Live Demo on coliru

    因此, 66535.0f / (max - min) 所以,在进入循环之前计算这个因子是值得的。

    推荐文章