• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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"""Verifies sensitivities on RAW images."""
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
28
29GR_PLANE_IDX = 1  # GR plane index in RGGB data
30IMG_STATS_GRID = 9  # Center 11.11%
31NAME = os.path.splitext(os.path.basename(__file__))[0]
32NUM_SENS_STEPS = 5
33VAR_THRESH = 1.01  # Each shot must be 1% noisier than previous
34
35
36def define_raw_stats_fmt(props):
37  """Define format with active array width and height."""
38  aaw = (props['android.sensor.info.preCorrectionActiveArraySize']['right'] -
39         props['android.sensor.info.preCorrectionActiveArraySize']['left'])
40  aah = (props['android.sensor.info.preCorrectionActiveArraySize']['bottom'] -
41         props['android.sensor.info.preCorrectionActiveArraySize']['top'])
42  logging.debug('Active array W,H: %d,%d', aaw, aah)
43  return {'format': 'rawStats',
44          'gridWidth': aaw // IMG_STATS_GRID,
45          'gridHeight': aah // IMG_STATS_GRID}
46
47
48class RawSensitivityTest(its_base_test.ItsBaseTest):
49  """Capture a set of raw images with increasing gains and measure the noise."""
50
51  def test_raw_sensitivity(self):
52    logging.debug('Starting %s', NAME)
53    with its_session_utils.ItsSession(
54        device_id=self.dut.serial,
55        camera_id=self.camera_id,
56        hidden_physical_id=self.hidden_physical_id) as cam:
57      props = cam.get_camera_properties()
58      props = cam.override_with_hidden_physical_camera_props(props)
59      camera_properties_utils.skip_unless(
60          camera_properties_utils.raw16(props) and
61          camera_properties_utils.manual_sensor(props) and
62          camera_properties_utils.read_3a(props) and
63          camera_properties_utils.per_frame_control(props) and
64          not camera_properties_utils.mono_camera(props))
65      name_with_log_path = os.path.join(self.log_path, NAME)
66
67      # Load chart for scene (chart_distance=0 for no chart scaling)
68      its_session_utils.load_scene(
69          cam, props, self.scene, self.tablet, chart_distance=0)
70
71      # Expose for the scene with min sensitivity
72      sens_min, _ = props['android.sensor.info.sensitivityRange']
73      # Digital gains might not be visible on RAW data
74      sens_max = props['android.sensor.maxAnalogSensitivity']
75      sens_step = (sens_max - sens_min) // NUM_SENS_STEPS
76
77      # Intentionally blur images for noise measurements
78      s_ae, e_ae, _, _, _ = cam.do_3a(do_af=False, get_results=True)
79      s_e_prod = s_ae * e_ae
80
81      sensitivities = list(range(sens_min, sens_max, sens_step))
82      variances = []
83      for s in sensitivities:
84        e = int(s_e_prod / float(s))
85        req = capture_request_utils.manual_capture_request(s, e, 0)
86
87        # Capture in rawStats to reduce test run time
88        fmt = define_raw_stats_fmt(props)
89        cap = cam.do_capture(req, fmt)
90
91        if self.debug_mode:
92          img = image_processing_utils.convert_capture_to_rgb_image(
93              cap, props=props)
94          image_processing_utils.write_image(
95              img, f'{name_with_log_path}_{s}_{e}ns.jpg', True)
96
97        # Measure variance
98        _, var_image = image_processing_utils.unpack_rawstats_capture(cap)
99        cfa_idxs = image_processing_utils.get_canonical_cfa_order(props)
100        white_level = float(props['android.sensor.info.whiteLevel'])
101        var = var_image[IMG_STATS_GRID//2, IMG_STATS_GRID//2,
102                        cfa_idxs[GR_PLANE_IDX]]/white_level**2
103        logging.debug('s=%d, e=%d, var=%e', s, e, var)
104        variances.append(var)
105
106      # Create plot
107      pylab.figure(NAME)
108      pylab.plot(sensitivities, variances, '-ro')
109      pylab.xticks(sensitivities)
110      pylab.xlabel('Sensitivities')
111      pylab.ylabel('Image Center Patch Variance')
112      pylab.ticklabel_format(axis='y', style='sci', scilimits=(-6, -6))
113      pylab.title(NAME)
114      matplotlib.pyplot.savefig(f'{name_with_log_path}_variances.png')
115
116      # Test that each shot is noisier than previous
117      for i in range(len(variances) - 1):
118        if variances[i] >= variances[i+1]/VAR_THRESH:
119          raise AssertionError(f'variances [i]: {variances[i]:5f}, [i+1]: '
120                               f'{variances[i+1]:.5f}, THRESH: {VAR_THRESH}')
121
122if __name__ == '__main__':
123  test_runner.main()
124