Debian Codegraph @

utils/tuning/libtuning/modules/lux/lux.py

raw
1 # SPDX-License-Identifier: GPL-2.0-or-later
2 #
3 # Copyright (C) 2019, Raspberry Pi Ltd
4 # Copyright (C) 2025, Ideas on Board
5 #
6 # Base Lux tuning module
7
8 from ..module import Module
9
10 import logging
11 import numpy as np
12
13 logger = logging.getLogger(__name__)
14
15
16 class Lux(Module):
17 type = 'lux'
18 hr_name = 'Lux (Base)'
19 out_name = 'GenericLux'
20
21 def __init__(self, debug: list):
22 super().__init__()
23
24 self.debug = debug
25
26 def calculate_lux_reference_values(self, images):
27 # The lux calibration is done on a single image. For best effects, the
28 # image with lux level closest to 1000 is chosen.
29 imgs = [img for img in images if img.macbeth is not None]
30 lux_values = [img.lux for img in imgs]
31 index = lux_values.index(min(lux_values, key=lambda l: abs(1000 - l)))
32 img = imgs[index]
33 logger.info(f'Selected image {img.name} for lux calibration')
34
35 if img.lux < 50:
36 logger.warning(f'A Lux level of {img.lux} is very low for proper lux calibration')
37
38 ref_y = self.calculate_y(img)
39 exposure_time = img.exposure
40 gain = img.againQ8_norm
41 aperture = 1
42 logger.info(f'RefY:{ref_y} Exposure time:{exposure_time}µs Gain:{gain} Aperture:{aperture}')
43 return {'referenceY': ref_y,
44 'referenceExposureTime': exposure_time,
45 'referenceAnalogueGain': gain,
46 'referenceDigitalGain': 1.0,
47 'referenceLux': img.lux}
48
49 def calculate_y(self, img):
50 max16Bit = 0xffff
51 # Average over all grey patches.
52 ap_r = np.mean(img.patches[0][3::4]) / max16Bit
53 ap_g = (np.mean(img.patches[1][3::4]) + np.mean(img.patches[2][3::4])) / 2 / max16Bit
54 ap_b = np.mean(img.patches[3][3::4]) / max16Bit
55 logger.debug(f'Averaged grey patches: Red: {ap_r}, Green: {ap_g}, Blue: {ap_b}')
56
57 # Calculate white balance gains.
58 gr = ap_g / ap_r
59 gb = ap_g / ap_b
60 logger.debug(f'WB gains: Red: {gr} Blue: {gb}')
61
62 # Calculate the mean Y value of the whole image
63 a_r = np.mean(img.channels[0]) * gr
64 a_g = (np.mean(img.channels[1]) + np.mean(img.channels[2])) / 2
65 a_b = np.mean(img.channels[3]) * gb
66 y = 0.299 * a_r + 0.587 * a_g + 0.114 * a_b
67 y /= max16Bit
68
69 return y
70