Skip to content

Instantly share code, notes, and snippets.

@matthewepler
Forked from hexagon5un/gamma.py
Last active April 26, 2023 03:14
Show Gist options
  • Save matthewepler/c6a206aa93719236da53ece060549608 to your computer and use it in GitHub Desktop.
Save matthewepler/c6a206aa93719236da53ece060549608 to your computer and use it in GitHub Desktop.
# Creates a gamma-corrected lookup table by @hexagon5un
# 04/23: updated file handle func and template strings for python 3,
# uses byte datatype instead of int,
# uses PROGMEM for storing table in memory (accessed with pgm_read_byte in Arduino),
# added explanatory comments and number padding (@matthewepler)
import math
def gamma(nsteps, gamma):
gammaedUp = [math.pow(x, gamma) for x in range(nsteps)]
return [x/max(gammaedUp) for x in gammaedUp]
def rounder(topValue, gammas):
return [min(topValue, round(x*topValue)) for x in gammas]
if __name__ == "__main__":
myGamma = 2.3 # usually a number between 1 and 3 with 2.0 - 2.3 being most common
steps = 256 # bit resolution (8-bit = 256, 12-bit = 4096)
maxVal = 255 # the maximum value, usually the same value as "steps" - 1
# open a new file, write a header and declare a variable for the table
output = open('gamma.h', 'w');
output.write(f'const byte PROGMEM gamma[{steps}] = ')
output.write('{\n')
cols = 16 # number of columns to appear in the table
colCounter = 0;
totalCounter = 0;
for value in rounder(maxVal, gamma(steps, myGamma)):
# write the value, padded with spaces for readability
output.write(f'{value:>3}')
colCounter += 1
totalCounter += 1
if totalCounter < steps:
# ensure last value in array is not followed by a comma
output.write(',');
if colCounter % 16 == 0:
output.write('\n')
colCounter = 0;
output.write("};\n")
output.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment