| 48 | } |
| 49 | |
| 50 | std::shared_ptr<ImageBuffer> loadImagePFM(const DeviceRef& device, |
| 51 | const std::string& filename, |
| 52 | DataType dataType, |
| 53 | Storage storage) |
| 54 | { |
| 55 | // Open the file |
| 56 | std::ifstream file(filename, std::ios::binary); |
| 57 | if (file.fail()) |
| 58 | throw std::runtime_error("cannot open image file: '" + filename + "'"); |
| 59 | |
| 60 | // Read the header |
| 61 | std::string id; |
| 62 | file >> id; |
| 63 | size_t C; |
| 64 | if (id == "PF") |
| 65 | C = 3; |
| 66 | else if (id == "Pf") |
| 67 | C = 1; |
| 68 | else if (id == "P=") |
| 69 | C = 2; // non-standard 2-channel format |
| 70 | else |
| 71 | throw std::runtime_error("invalid PFM image"); |
| 72 | |
| 73 | if (dataType == DataType::Undefined) |
| 74 | dataType = DataType::Float32; |
| 75 | |
| 76 | size_t H, W; |
| 77 | file >> W >> H; |
| 78 | |
| 79 | float scale; |
| 80 | file >> scale; |
| 81 | |
| 82 | file.get(); // skip newline |
| 83 | |
| 84 | if (file.fail()) |
| 85 | throw std::runtime_error("invalid PFM image"); |
| 86 | |
| 87 | if (scale >= 0.f) |
| 88 | throw std::runtime_error("big-endian PFM images are not supported"); |
| 89 | scale = fabs(scale); |
| 90 | |
| 91 | // Read the pixels |
| 92 | auto image = std::make_shared<ImageBuffer>(device, W, H, C, dataType, storage); |
| 93 | |
| 94 | for (size_t h = 0; h < H; ++h) |
| 95 | { |
| 96 | for (size_t w = 0; w < W; ++w) |
| 97 | { |
| 98 | for (size_t c = 0; c < C; ++c) |
| 99 | { |
| 100 | float x; |
| 101 | file.read(reinterpret_cast<char*>(&x), sizeof(float)); |
| 102 | if (file.fail()) |
| 103 | throw std::runtime_error("invalid PFM image: error reading pixel data"); |
| 104 | image->set((size_t(H-1-h)*W + w) * C + c, x * scale); |
| 105 | } |
| 106 | } |
| 107 | } |