1# Copyright 2014 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import os.path
16import its.caps
17import its.device
18import its.image
19import its.objects
20import matplotlib
21from matplotlib import pylab
22import numpy
23
24LOCKED = 3
25MAX_LUMA_DELTA_THRESH = 0.05
26NAME = os.path.basename(__file__).split('.')[0]
27THRESH_CONVERGE_FOR_EV = 8  # AE must converge in this num auto reqs for EV
28
29
30def main():
31    """Tests that EV compensation is applied."""
32
33    with its.device.ItsSession() as cam:
34        props = cam.get_camera_properties()
35        its.caps.skip_unless(its.caps.manual_sensor(props) and
36                             its.caps.manual_post_proc(props) and
37                             its.caps.per_frame_control(props) and
38                             its.caps.ev_compensation(props))
39
40        mono_camera = its.caps.mono_camera(props)
41        debug = its.caps.debug_mode()
42        largest_yuv = its.objects.get_largest_yuv_format(props)
43        if debug:
44            fmt = largest_yuv
45        else:
46            match_ar = (largest_yuv['width'], largest_yuv['height'])
47            fmt = its.objects.get_smallest_yuv_format(props, match_ar=match_ar)
48
49        ev_compensation_range = props['android.control.aeCompensationRange']
50        range_min = ev_compensation_range[0]
51        range_max = ev_compensation_range[1]
52        ev_per_step = its.objects.rational_to_float(
53                props['android.control.aeCompensationStep'])
54        steps_per_ev = int(round(1.0 / ev_per_step))
55        ev_steps = range(range_min, range_max + 1, steps_per_ev)
56        imid = len(ev_steps) / 2
57        ev_shifts = [pow(2, step * ev_per_step) for step in ev_steps]
58        lumas = []
59
60        # Converge 3A, and lock AE once converged. skip AF trigger as
61        # dark/bright scene could make AF convergence fail and this test
62        # doesn't care the image sharpness.
63        cam.do_3a(ev_comp=0, lock_ae=True, do_af=False, mono_camera=mono_camera)
64
65        for ev in ev_steps:
66
67            # Capture a single shot with the same EV comp and locked AE.
68            req = its.objects.auto_capture_request()
69            req['android.control.aeExposureCompensation'] = ev
70            req['android.control.aeLock'] = True
71            # Use linear tone curve to avoid brightness being impacted
72            # by tone curves.
73            req['android.tonemap.mode'] = 0
74            req['android.tonemap.curve'] = {
75                    'red': [0.0, 0.0, 1.0, 1.0],
76                    'green': [0.0, 0.0, 1.0, 1.0],
77                    'blue': [0.0, 0.0, 1.0, 1.0]}
78            caps = cam.do_capture([req]*THRESH_CONVERGE_FOR_EV, fmt)
79
80            for cap in caps:
81                if cap['metadata']['android.control.aeState'] == LOCKED:
82                    y = its.image.convert_capture_to_planes(cap)[0]
83                    tile = its.image.get_image_patch(y, 0.45, 0.45, 0.1, 0.1)
84                    lumas.append(its.image.compute_image_means(tile)[0])
85                    break
86            assert cap['metadata']['android.control.aeState'] == LOCKED
87
88        print 'ev_step_size_in_stops', ev_per_step
89        shift_mid = ev_shifts[imid]
90        luma_normal = lumas[imid] / shift_mid
91        expected_lumas = [min(1.0, luma_normal*ev_shift) for ev_shift in ev_shifts]
92
93        pylab.plot(ev_steps, lumas, '-ro')
94        pylab.plot(ev_steps, expected_lumas, '-bo')
95        pylab.title(NAME)
96        pylab.xlabel('EV Compensation')
97        pylab.ylabel('Mean Luma (Normalized)')
98
99        matplotlib.pyplot.savefig('%s_plot_means.png' % (NAME))
100
101        luma_diffs = [expected_lumas[i]-lumas[i] for i in range(len(ev_steps))]
102        max_diff = max(abs(i) for i in luma_diffs)
103        avg_diff = abs(numpy.array(luma_diffs)).mean()
104        print 'Max delta between modeled and measured lumas:', max_diff
105        print 'Avg delta between modeled and measured lumas:', avg_diff
106        assert max_diff < MAX_LUMA_DELTA_THRESH, 'diff: %.3f, THRESH: %.2f' % (
107                max_diff, MAX_LUMA_DELTA_THRESH)
108
109
110if __name__ == '__main__':
111    main()
112