1# Copyright 2013 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"""Verifies android.sensor.sensitivity parameter is applied."""
15
16
17import logging
18import os.path
19import matplotlib
20from matplotlib import pylab
21from mobly import test_runner
22
23import its_base_test
24import camera_properties_utils
25import capture_request_utils
26import image_processing_utils
27import its_session_utils
28import target_exposure_utils
29
30COLORS = ['R', 'G', 'B']
31NAME = os.path.splitext(os.path.basename(__file__))[0]
32NUM_STEPS = 5
33PATCH_H = 0.1  # center 10%
34PATCH_W = 0.1
35PATCH_X = 0.5 - PATCH_W/2
36PATCH_Y = 0.5 - PATCH_H/2
37
38
39class ParamSensitivityTest(its_base_test.ItsBaseTest):
40  """Test that the android.sensor.sensitivity parameter is applied."""
41
42  def test_param_sensitivity(self):
43    logging.debug('Starting %s', NAME)
44    sensitivities = None
45    r_means = []
46    g_means = []
47    b_means = []
48
49    with its_session_utils.ItsSession(
50        device_id=self.dut.serial,
51        camera_id=self.camera_id,
52        hidden_physical_id=self.hidden_physical_id) as cam:
53      props = cam.get_camera_properties()
54      props = cam.override_with_hidden_physical_camera_props(props)
55      log_path = self.log_path
56      test_name_with_path = os.path.join(log_path, NAME)
57
58      # check SKIP conditions
59      camera_properties_utils.skip_unless(
60          camera_properties_utils.compute_target_exposure(props))
61
62      # Load chart for scene
63      its_session_utils.load_scene(
64          cam, props, self.scene, self.tablet, self.chart_distance)
65
66      # Initialize requests
67      sync_latency = camera_properties_utils.sync_latency(props)
68      largest_yuv = capture_request_utils.get_largest_yuv_format(props)
69      match_ar = (largest_yuv['width'], largest_yuv['height'])
70      fmt = capture_request_utils.get_smallest_yuv_format(
71          props, match_ar=match_ar)
72
73      expt, _ = target_exposure_utils.get_target_exposure_combos(
74          log_path, cam)['midSensitivity']
75      sens_range = props['android.sensor.info.sensitivityRange']
76      sens_step = (sens_range[1] - sens_range[0]) / float(NUM_STEPS-1)
77      sensitivities = [
78          int(sens_range[0] + i * sens_step) for i in range(NUM_STEPS)]
79
80      for s in sensitivities:
81        logging.debug('Capturing with sensitivity: %d', s)
82        req = capture_request_utils.manual_capture_request(s, expt)
83        cap = its_session_utils.do_capture_with_latency(
84            cam, req, sync_latency, fmt)
85        img = image_processing_utils.convert_capture_to_rgb_image(cap)
86        image_processing_utils.write_image(
87            img, f'{test_name_with_path}_iso={s}.jpg')
88        patch = image_processing_utils.get_image_patch(
89            img, PATCH_X, PATCH_Y, PATCH_W, PATCH_H)
90        rgb_means = image_processing_utils.compute_image_means(patch)
91        r_means.append(rgb_means[0])
92        g_means.append(rgb_means[1])
93        b_means.append(rgb_means[2])
94
95    logging.debug('R means: %s', str(r_means))
96    logging.debug('G means: %s', str(g_means))
97    logging.debug('B means: %s', str(b_means))
98
99    # Draw plot
100    pylab.figure(NAME)
101    pylab.plot(sensitivities, r_means, '-ro')
102    pylab.plot(sensitivities, g_means, '-go')
103    pylab.plot(sensitivities, b_means, '-bo')
104    pylab.ylim([0, 1])
105    pylab.title(NAME)
106    pylab.xlabel('Gain (ISO)')
107    pylab.ylabel('RGB means')
108    matplotlib.pyplot.savefig(f'{test_name_with_path}_plot_means.png')
109
110    # Test for pass/fail: check that each shot is brighter than previous
111    for i, means in enumerate([r_means, g_means, b_means]):
112      for j in range(len(means)-1):
113        if means[j+1] <= means[j]:
114          raise AssertionError(f'{COLORS[i]} cap {j} means[j+1]: '
115                               f'{means[j+1]:.3f}, means[j]: {means[j]:.3f}')
116
117if __name__ == '__main__':
118  test_runner.main()
119
120