Skip to content
Myr

srgb.py

This file

Path

srgb.py

71 lines · 2.2 KiB · Python

Last changed by

Implement gamma-correct blendingDaniel Eklöfbefore adoption2d19826

History of this file

Take it

1#!/usr/bin/env python323import argparse4import math5import sys678# Note: we use a pure gamma 2.2 function, rather than the piece-wise9# sRGB transfer function, since that is what all compositors do.1011def srgb_to_linear(f: float) -> float:12    assert(f >= 0 and f <= 1.0)13    return math.pow(f, 2.2)141516def linear_to_srgb(f: float) -> float:17    return math.pow(f, 1 / 2.2)181920def main():21    parser = argparse.ArgumentParser()22    parser.add_argument('c_output', type=argparse.FileType('w'))23    parser.add_argument('h_output', type=argparse.FileType('w'))24    opts = parser.parse_args()2526    linear_table: list[int] = []2728    for i in range(256):29        linear_table.append(int(srgb_to_linear(float(i) / 255) * 65535 + 0.5))303132    opts.h_output.write("#pragma once\n")33    opts.h_output.write("#include <stdint.h>\n")34    opts.h_output.write("\n")35    opts.h_output.write('/* 8-bit input, 16-bit output */\n')36    opts.h_output.write("extern const uint16_t srgb_decode_8_to_16_table[256];")3738    opts.h_output.write('\n')39    opts.h_output.write('static inline uint16_t\n')40    opts.h_output.write('srgb_decode_8_to_16(uint8_t v)\n')41    opts.h_output.write('{\n')42    opts.h_output.write('    return srgb_decode_8_to_16_table[v];\n')43    opts.h_output.write('}\n')4445    opts.h_output.write('\n')46    opts.h_output.write('/* 8-bit input, 8-bit output */\n')47    opts.h_output.write("extern const uint8_t srgb_decode_8_to_8_table[256];\n")4849    opts.h_output.write('\n')50    opts.h_output.write('static inline uint8_t\n')51    opts.h_output.write('srgb_decode_8_to_8(uint8_t v)\n')52    opts.h_output.write('{\n')53    opts.h_output.write('    return srgb_decode_8_to_8_table[v];\n')54    opts.h_output.write('}\n')5556    opts.c_output.write('#include "srgb.h"\n')57    opts.c_output.write('\n')5859    opts.c_output.write("const uint16_t srgb_decode_8_to_16_table[256] = {\n")60    for i in range(256):61        opts.c_output.write(f'    {linear_table[i]},\n')62    opts.c_output.write('};\n')6364    opts.c_output.write("const uint8_t srgb_decode_8_to_8_table[256] = {\n")65    for i in range(256):66        opts.c_output.write(f'    {linear_table[i] >> 8},\n')67    opts.c_output.write('};\n')686970if __name__ == '__main__':71    sys.exit(main())