summaryrefslogtreecommitdiff
path: root/utils/rkisp1/rkisp1_lsc_rpi_to_libcamera.py
blob: e86a88adc4924373fc49697f00c35f359452eae1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python3

import argparse
import json
import numpy as np
import scipy.ndimage
import sys
import yaml


def update_yaml_config(config, reds, green, blues):
    with open(config, 'r') as config:
        data = yaml.safe_load(config)

        xy_sizes = [0.0625, 0.0625, 0.0625,
                    0.0625, 0.0625, 0.0625, 0.0625, 0.0625]

        lsc_config = {}
        lsc_config['x-size'] = []
        lsc_config['y-size'] = []
        for size in xy_sizes:
            lsc_config['x-size'].append(size)
            lsc_config['y-size'].append(size)
        lsc_config['sets'] = []

        for temperature in reds.keys():
            red_table = reds[temperature].flatten()
            blue_table = blues[temperature].flatten()

            ct_set = {}
            ct_set['ct'] = temperature
            ct_set['r'] = []
            ct_set['gr'] = []
            ct_set['gb'] = []
            ct_set['b'] = []

            for f in red_table:
                i = round(f * 1024)
                ct_set['r'].append(i)

            for f in green:
                i = round(f * 1024)

                ct_set['gr'].append(i)
                ct_set['gb'].append(i)

            for f in blue_table:
                i = round(f * 1024)

                ct_set['b'].append(i)

            lsc_config['sets'].append(ct_set)

        lsc = {'LensShadingCorrection': lsc_config}

        # Remove any existing LensShadingCorrection section
        algos = data['algorithms']
        for algo in algos:
            for k in algo.keys():
                if k == 'LensShadingCorrection':
                    algos.remove(algo)
                    break

        algos.append(lsc)
        print(data)
        return data


def sort_by_temperature(calibrations):
    data = {}
    for entry in calibrations:
        temp = entry['ct']
        table = np.array(entry['table']).reshape(12, 16)

        data[temp] = table

    return data


def parse_lsc_data(filename):
    with open(filename, 'r') as tuning_file:
        for algo in json.load(tuning_file)['algorithms']:
            for (k, v) in algo.items():
                if k == 'rpi.alsc':
                    return v

    raise Exception("Cannot find LSC tuning data in file " + filename)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--file', required=True,
                        help='Tuning file to parse')
    parser.add_argument('-t', '--temperature', help='Color temperature')
    # todo: Do not make this mandatory and default to stdio
    parser.add_argument('-a', '--append', required=True,
                        help='RkISP configuration file to append LSC tables to')

    args = parser.parse_args()

    lsc_data = parse_lsc_data(args.file)

    luminance_strength = lsc_data['luminance_strength']
    luma = np.array(lsc_data['luminance_lut']).reshape(12, 16)
    green = (luma - 1) * luminance_strength + 1

    cr_data = sort_by_temperature(lsc_data['calibrations_Cr'])
    cb_data = sort_by_temperature(lsc_data['calibrations_Cb'])

    reds = {}
    blues = {}

    for temperature in cr_data.keys():
        cr = cr_data[temperature]
        cb = cb_data[temperature]

        red = cr * green
        red = scipy.ndimage.zoom(red, (17 / 12, 17 / 16))
        red /= red.min()

        blue = cb * green
        blue = scipy.ndimage.zoom(blue, (17 / 12, 17 / 16))
        blue /= blue.min()

        reds[temperature] = red
        blues[temperature] = blue

    green = scipy.ndimage.zoom(green, (17 / 12, 17 / 16))
    green /= green.min()

    new_config = update_yaml_config(args.append, reds, green.flatten(), blues)
    with open(args.append, 'w') as config:
        yaml.safe_dump(new_config, config)

    return 0


if __name__ == '__main__':
    sys.exit(main())