Rename men_at_work to water_scene, crop and zoom IMG_2412.jpg for continuity
[stop_motion.git] / gamma.py
1 #!/usr/bin/env python3
2
3 import imageio
4 import numpy
5
6 def read_image(in_file):
7   # read double image
8   image = imageio.imread(in_file) / 255.
9
10   # gamma decode
11   temp = image if len(image.shape) == 2 else image[:, :, :3] # skip alpha
12   linear = temp < .0031308 * 12.92
13   temp[linear] /= 12.92
14   temp[~linear] = ((temp[~linear] + .055) / 1.055) ** 2.4
15
16   return image
17
18 def write_image(out_file, image):
19   image = numpy.copy(image)
20
21   # gamma encode
22   temp = image if len(image.shape) == 2 else image[:, :, :3] # skip alpha
23   linear = temp < .0031308
24   temp[linear] *= 12.92
25   temp[~linear] = 1.055 * temp[~linear] ** (1. / 2.4) - .055
26
27   # write double image
28   image[image < 0.] = 0.
29   image[image > 1.] = 1.
30   imageio.imwrite(
31     out_file,
32     numpy.round(image * 255.).astype(numpy.uint8)
33   )
34
35 if __name__ == '__main__':
36   import sys
37   
38   if len(sys.argv) < 3:
39     print(f'usage: {sys.argv[0]:s} in_file out_file')
40     sys.exit(1)
41   in_file = sys.argv[1]
42   out_file = sys.argv[2]
43   
44   write_image(out_file, read_image(in_file))