1# Copyright 2016 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
16
17import its.caps
18import its.cv2image
19import its.device
20import its.image
21import its.objects
22import numpy as np
23
24NUM_IMGS = 12
25FRAME_TIME_TOL = 10  # ms
26SHARPNESS_TOL = 0.10  # percentage
27POSITION_TOL = 0.10  # percentage
28VGA_WIDTH = 640
29VGA_HEIGHT = 480
30NAME = os.path.basename(__file__).split('.')[0]
31CHART_FILE = os.path.join(os.environ['CAMERA_ITS_TOP'], 'pymodules', 'its',
32                          'test_images', 'ISO12233.png')
33CHART_HEIGHT = 13.5  # cm
34CHART_DISTANCE = 30.0  # cm
35CHART_SCALE_START = 0.65
36CHART_SCALE_STOP = 1.35
37CHART_SCALE_STEP = 0.025
38
39
40def test_lens_movement_reporting(cam, props, fmt, sensitivity, exp, af_fd):
41    """Return fd, sharpness, lens state of the output images.
42
43    Args:
44        cam: An open device session.
45        props: Properties of cam
46        fmt: dict; capture format
47        sensitivity: Sensitivity for the 3A request as defined in
48            android.sensor.sensitivity
49        exp: Exposure time for the 3A request as defined in
50            android.sensor.exposureTime
51        af_fd: Focus distance for the 3A request as defined in
52            android.lens.focusDistance
53
54    Returns:
55        Object containing reported sharpness of the output image, keyed by
56        the following string:
57            'sharpness'
58    """
59
60    # initialize chart class
61    chart = its.cv2image.Chart(CHART_FILE, CHART_HEIGHT, CHART_DISTANCE,
62                               CHART_SCALE_START, CHART_SCALE_STOP,
63                               CHART_SCALE_STEP)
64
65    # find chart location
66    xnorm, ynorm, wnorm, hnorm = chart.locate(cam, props, fmt, sensitivity,
67                                              exp, af_fd)
68
69    # initialize variables and take data sets
70    data_set = {}
71    white_level = int(props['android.sensor.info.whiteLevel'])
72    min_fd = props['android.lens.info.minimumFocusDistance']
73    fds = [af_fd, min_fd]
74    fds = sorted(fds * NUM_IMGS)
75    reqs = []
76    for i, fd in enumerate(fds):
77        reqs.append(its.objects.manual_capture_request(sensitivity, exp))
78        reqs[i]['android.lens.focusDistance'] = fd
79    caps = cam.do_capture(reqs, fmt)
80    for i, cap in enumerate(caps):
81        data = {'fd': fds[i]}
82        data['loc'] = cap['metadata']['android.lens.focusDistance']
83        data['lens_moving'] = (cap['metadata']['android.lens.state']
84                               == 1)
85        timestamp = cap['metadata']['android.sensor.timestamp']
86        if i == 0:
87            timestamp_init = timestamp
88        timestamp -= timestamp_init
89        timestamp *= 1E-6
90        data['timestamp'] = timestamp
91        print ' focus distance (diopters): %.3f' % data['fd']
92        print ' current lens location (diopters): %.3f' % data['loc']
93        print ' lens moving %r' % data['lens_moving']
94        y, _, _ = its.image.convert_capture_to_planes(cap, props)
95        y = its.image.flip_mirror_img_per_argv(y)
96        chart = its.image.normalize_img(its.image.get_image_patch(y,
97                                                                  xnorm, ynorm,
98                                                                  wnorm, hnorm))
99        its.image.write_image(chart, '%s_i=%d_chart.jpg' % (NAME, i))
100        data['sharpness'] = white_level*its.image.compute_image_sharpness(chart)
101        print 'Chart sharpness: %.1f\n' % data['sharpness']
102        data_set[i] = data
103    return data_set
104
105
106def main():
107    """Test if focus distance is properly reported.
108
109    Capture images at a variety of focus locations.
110    """
111
112    print '\nStarting test_lens_movement_reporting.py'
113    with its.device.ItsSession() as cam:
114        props = cam.get_camera_properties()
115        its.caps.skip_unless(not its.caps.fixed_focus(props))
116        its.caps.skip_unless(its.caps.lens_approx_calibrated(props))
117        min_fd = props['android.lens.info.minimumFocusDistance']
118        fmt = {'format': 'yuv', 'width': VGA_WIDTH, 'height': VGA_HEIGHT}
119
120        # Get proper sensitivity, exposure time, and focus distance with 3A.
121        s, e, _, _, fd = cam.do_3a(get_results=True)
122
123        # Get sharpness for each focal distance
124        d = test_lens_movement_reporting(cam, props, fmt, s, e, fd)
125        for k in sorted(d):
126            print ('i: %d\tfd: %.3f\tlens location (diopters): %.3f \t'
127                   'sharpness: %.1f  \tlens_moving: %r \t'
128                   'timestamp: %.1fms' % (k, d[k]['fd'], d[k]['loc'],
129                                          d[k]['sharpness'],
130                                          d[k]['lens_moving'],
131                                          d[k]['timestamp']))
132
133        # assert frames are consecutive
134        print 'Asserting frames are consecutive'
135        times = [v['timestamp'] for v in d.itervalues()]
136        diffs = np.gradient(times)
137        assert np.isclose(np.amax(diffs)-np.amax(diffs), 0, atol=FRAME_TIME_TOL)
138
139        # remove data when lens is moving
140        for k in sorted(d):
141            if d[k]['lens_moving']:
142                del d[k]
143
144        # split data into min_fd and af data for processing
145        d_min_fd = {}
146        d_af_fd = {}
147        for k in sorted(d):
148            if d[k]['fd'] == min_fd:
149                d_min_fd[k] = d[k]
150            if d[k]['fd'] == fd:
151                d_af_fd[k] = d[k]
152
153        # assert reported locations are close at af_fd
154        print 'Asserting lens location of af_fd data'
155        min_loc = min([v['loc'] for v in d_af_fd.itervalues()])
156        max_loc = max([v['loc'] for v in d_af_fd.itervalues()])
157        assert np.isclose(min_loc, max_loc, rtol=POSITION_TOL)
158        # assert reported sharpness is close at af_fd
159        print 'Asserting sharpness of af_fd data'
160        min_sharp = min([v['sharpness'] for v in d_af_fd.itervalues()])
161        max_sharp = max([v['sharpness'] for v in d_af_fd.itervalues()])
162        assert np.isclose(min_sharp, max_sharp, rtol=SHARPNESS_TOL)
163        # assert reported location is close to assign location for af_fd
164        print 'Asserting lens location close to assigned fd for af_fd data'
165        assert np.isclose(d_af_fd[0]['loc'], d_af_fd[0]['fd'],
166                          rtol=POSITION_TOL)
167
168        # assert reported location is close for min_fd captures
169        print 'Asserting lens location similar min_fd data'
170        min_loc = min([v['loc'] for v in d_min_fd.itervalues()])
171        max_loc = max([v['loc'] for v in d_min_fd.itervalues()])
172        assert np.isclose(min_loc, max_loc, rtol=POSITION_TOL)
173        # assert reported sharpness is close at min_fd
174        print 'Asserting sharpness of min_fd data'
175        min_sharp = min([v['sharpness'] for v in d_min_fd.itervalues()])
176        max_sharp = max([v['sharpness'] for v in d_min_fd.itervalues()])
177        assert np.isclose(min_sharp, max_sharp, rtol=SHARPNESS_TOL)
178        # assert reported location is close to assign location for min_fd
179        print 'Asserting lens location close to assigned fd for min_fd data'
180        assert np.isclose(d_min_fd[NUM_IMGS*2-1]['loc'],
181                          d_min_fd[NUM_IMGS*2-1]['fd'], rtol=POSITION_TOL)
182
183
184if __name__ == '__main__':
185    main()
186